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.1.
Sort the array if $sort modifier is specified.2.
Slice the array if $slice modifier is specified.3.
Store the array.4.
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: