MongoDB $push Operator
In the following examples, we are working with
Database: w3wiki
Collection: contributor
Document: two documents that contain the details of the contributor in the form of field-value pairs
Appending a single value to an array example using $push operator
In this example, we are appending a single value, i.e., “C++” to an array field, i.e., language field in the document that satisfy the condition(name: “Rohit”).
Query:
db.contributor.update({name: "Rohit"}, {$push: {language: "C++"}})
Output:
Appending multiple values to an array using $push operator
In this example, we are appending multiple values, i.e., [“C”, “Ruby”, “Go”] to an array field, i.e., language field in the document that satisfy the condition(name: “Sumit”).
Query:
db.contributor.update({name: "Sumit"}, {$push: {language: {$each: ["C", "Ruby", "Go"]}}})
Output:
Appending multiple values to an array in the nested/embedded document using $push operator:
In this example, we are appending multiple values, i.e., [89, 76.4] to an array field, i.e., personal.semesterMarks field of a nested/embedded document.
Query:
db.contributor.update({name: "Sumit"},
{$push: {"personal.semesterMarks": {$each: [89, 76.4]}}})
Output:
Using modifiers with $push operator example
In this example, we are using multiple modifiers like $each, $sort, and $slice with $push operator.
Query:
db.contributor.update({name: "Rohit"},
{$push: { language: { $each: ["C", "Go"],
$sort: 1, $slice: 4}}})
Here,
- The $each modifier is used to add multiple documents to the language array.
- The $sort modifier is used to sort all the items of the modified language array in ascending.
- The $slice modifier is used to keep only the first four sorted items of the language array.
Output:
MongoDB $push Operator
MongoDB $push operator appends a value to the already existing array within a document.