Using Push & Pull Operators in Mongodb
The $Push and $Pull Operators Are a Part of Array Operators Designed to Modify Arrays in Mongodb Documents. in This Tutorial, I’ll Show You How the Push and...
The $push and $pull operators are a part of array operators designed to modify arrays in MongoDB documents. In this tutorial, I’ll show you how the push and pull operators work and how to use them with additional modifiers and conditions.
(This article is part of our MongoDB Guide. Use the right-hand menu to navigate.)
What are push and pull operators?
Push and Pull are the two operations used to add and remove elements from arrays in MongoDB documents. Pushing and pulling elements are done using the MongoDB $push and $pull operators, respectively:
- The $push operator appends a specified value to an array.
- The $pull operator removes values from an array that matches a specified condition.
Basic syntax of $push operator
{ $push: { <field1>: <value1>, ... } }
Basic syntax of $pull operator
{ $pull: { <field1>: <value|condition>, ... } }
Let’s look at each in more detail, including how they work and how you can use them.
Must Read
How MongoDB $push operator works
You can see the $push operator takes two arguments:
- The array field
- The value to be appended to the specified array field
If the array field is not present in the document, the $push operator will create a new array field. However, if the specified field is not an array, MongoDB will return an error.
$push operator modifiers
The functionality of the $push operator can be further extended using the following modifiers.
- $each. The $each modifier is used to append multiple values to an array. If the $each operator is not specified, all values in the $push operator will be appended as a single item to the array field in the document.
- $slice. This limits the number of elements in the array. However, this must be used in conjunction with the $each modifier.
- $sort. The $sort modifiers orders the items in the array. This modifier also requires the use of $each modifier.
- $position. The $push operator appends a new item to the end of an array by default. Use the $position modifier if you want to explicitly specify the location where the item should be appended.
The $push operation is carried out in the following order, regardless of the order in which the modifiers are defined:
- Update the array to add elements in the specified positions.
- Sort the array if $sort modifier is specified.
- Slice the array if $slice modifier is specified.
- Store the array.
Next, we will look at how we can use MongoDB $push operations to manipulate documents. I’ll show a few examples, so jump to the one you need:
- Append a single value to an array
- Append multiple values to an array
- Use the $sort and $slice modifiers
- Use the $position modifier
For the base data set for these examples, I’ll use the “vehicledetails” collection.
db.vehicledetails.find().pretty()
Result:
Append a single value to an array
Let us see how we can append a single value to an array when an array field is present, and it’s not present. In all examples, the “_id” field is used to indicate which document the array should be added.
Example: No Array Field
A new array field will be created with the field name specified in the $push operator.
db.vehicledetails.update({"_id": ObjectId("5fbc52f05f9a62418038240d")}, {$push: {"vehicle_colours": "red"}})
Result:
Example: When the array Field is present
The new item will be appended at the end of the array.
db.vehicledetails.update({"_id": ObjectId("5fbc52f05f9a62418038240d")}, {$push: {"vehicle_colours": "green"}})
Result:
If we try to use the $push operator for a non-array field, it will result in an error. The following code returns an error as we are trying to append a value to the non-array field “make”.
db.vehicledetails.update({"_id": ObjectId("5fbc52f05f9a62418038240d")}, {$push: {"make": "green"}})
Result:
Append Multiple Values to an Array
You can append multiple values to an array with or without $each modifier.
Example: Multiple Values without $each modifier
If the $each modifier is not present, MongoDB will append all the values as a single value to the specified array field.
db.vehicledetails.update({"_id": ObjectId("5fbc52f55f9a62418038240e")}, {$push: {"vehicle_colours": ["blue", "red", "yellow"]}})
Result:
Here, you can see “blue”, “red”, and “yellow” are elements of a newly created array. But that array is just one element of the “vehical_colours” array.
Example: Multiple Values with $each modifier
When a $push operation is defined with the $each modifier, each element in the $push operation will be added to the array as individual items.
db.vehicledetails.update({"_id": ObjectId("5fbc52f55f9a62418038240e")}, {$push: {"vehicle_colours": { $each :["blue", "red", "yellow"]}}})
Result:
Here, “vehicle_colours” has three elements after $push operation.
Using the $sort and $slice Modifiers
In this section, we will demonstrate how to use the $sort and $slice modifiers using the following document in the “vehicledetails” collection.
Let us add the color “silver” to the “vehicle_colours” array field and sort the contents alphabetically (ascending order).
db.vehicledetails.update({"_id": ObjectId("5fbc52fb5f9a62418038240f")}, {$push: {"vehicle_colours": { $each :["silver", "orange"], $sort: 1}}})
Result:
The above output shows us that the new colors were added, and the array has been sorted alphabetically. In the following example, we will add the color “dark blue” to the array field while sorting alphabetically and using the $slice modifier to limit the array to 5 elements.
db.vehicledetails.update({"_id": ObjectId("5fbc52fb5f9a62418038240f")}, {$push: {"vehicle_colours": { $each :["dark blue"], $sort: 1, $slice: 5}}})
Result:
Using the $position Modifier
The $position modifier is used to specify the location in the array where the new item should be added. This will override the default behavior of appending the items to the end of the array.
In the following example, we will add the color “white” to the beginning of the array field “vehicle_colours”. In the “$position” modifier, zero (0) is used to indicate the first position (index 0) of the array.
db.vehicledetails.update({"_id": ObjectId("5fbc52fb5f9a62418038240f")}, {$push: {"vehicle_colours": { $each :["white"], $position: 0}}})
Result: