![]() |
VOOZH | about |
The $push operator in MongoDB adds values to an array field during updates, creating the field if it doesnβt exist, and can insert multiple values individually when used with $each.
{ $push: { <field1>: <value1>, ... } }{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... } }Processing Order with Modifiers
Note: Here the order in which the modifiers appear in the $push operator does not matter.
Below are the modifiers in MongoDB that can be used with $push operator.
| Modifier | Description |
|---|---|
| $each | It is used to append multiple values to the array field. |
| $slice | Limits the number of array elements after insertion and must be used with $each. |
| $sort | It is used to order items of the array and requires the use of the $each modifier. |
| $position | $position inserts at a specific index(requires $each), otherwise $push appends to last index. |
In the following examples, we are working with
Database: GeeksforGeeks
Collection: contributor
Document: Two documents that contain the details of the contributor in the form of field-value pairs
Appending a single value, i.e., "C++" to an array field, i.e., language field in the document that satisfies the condition(name: "Mateo").
db.contributor.updateOne({ name: "Mateo" }, { $push: { language: "C++" } })Output:
Appending multiple values, i.e., ["C", "Ruby", "Go"] to an array field, i.e., language field in the document that satisfy the condition (name: "Luca").
db.contributor.updateOne({ name: "Luca" }, { $push: { language: { $each: ["C", "Ruby", "Go"] } } })Output:
Appending multiple values, i.e., [89, 76.4] to an array field, i.e., personal.semesterMarks field of a nested/embedded document.
db.contributor.updateOne(
{ name: "Luca" },
{
$push: {
"personal.semesterMarks": {
$each: [89, 76.4]
}
}
}
)
Output:
Adds multiple values to an array, then sorts and limits the array size by truncating elements after sorting or insertion in one atomic update.
db.contributor.updateOne(
{ name: "Mateo" },
{
$push: {
language: {
$each: ["C", "Go"],
$sort: 1,
$slice: 4
}
}
}
)
Output:
$sort modifier sorts the modified language array in ascending order.Here are some uses of $push operator: