Example of MongoDB $push operator
If we want to append 95 to the array field achieve against the condition subjects is "gkn", the following mongodb command can be used -
db.student.update( { "subjects" : "gkn" },{ $push: { "achieve": 95 } });
Here in the above example the value 95 will be append into the array achieve, because the condition mentioned is matching for this operation.
To see the newly updated document -
db.student.find().pretty();
Output:
"_id" : 1,
"achieve" : [
70,
87,
90,
90,
65,
81,
95
],
"sem" : 1,
"subjects" : [
"phys",
"chem",
"maths ",
"gkn",
"stat",
"astro"
]
Combining $push with Other Operators for Updates
Modifiers of Push Operator in MongoDB
MongoDB provides various modifiers that can be used in conjunction with the $push in mongoDB to modify the behavior of the operation. The syntax of the $push operator with modifiers is,
db.collection.updateOne
{ <query> },
{ $push: { <field1>: { <modifier1>: <value1>, ... }, ... }}
)
The modifiers used along with the $push in mongoDB are executed in a defined order. The modifiers in the order of their execution are:
- The $each modifier allows appending multiple values to an array field. It accepts an array of values as input.
- The $sort modifier performs sorting operations in ascending or descending order as specified. This operator can only be used with the $each modifier.
- The $position modifier allows you to specify the index at which the new elements should be inserted in the array. It accepts a numeric value representing the desired index.
- The $slice modifier is used to limit the number of elements in the array field after performing the push operation. It accepts a numeric value which is the desired size of the array.
- The $addToSet modifier is used to ensure that the pushed value is unique within the array. The values specified will not be added to the array if the values already exist in the array.
Appending values into array
There are three type of appending the values in array:
- Appending a single value to an array
- Appending multiple values to an array
- Appending multiple values to an array in the nested/embedded document
1. Appending a single value to an array:
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”).
Syntax:
db.contributor.update({name: "Rohit"}, {$push: {language: "C++"}})
To append a single value, let's say orange, to the favorites array, we can use the following update query,
db.users.updateOne
{ "_id": 1 },
{ $push: { "favorites": "orange" } }
)
In the above query, the document is fetched using the _id. The favorites is the array field, and orange is the value that is to be pushed to the array. The modified document after the above using the operator push in MongoDB is,
{
"_id": 1,
"name": "Hari",
"favorites": ["apple", "banana", "orange"]
}
2. Appending multiple values to an array:
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”).
Syntax:
db.contributor.update({name: "Sumit"}, {$push: {language: {$each: ["C", "Ruby", "Go"]}}})
To append multiple values, let's say ["mango", "grape"], to the favorites array, we can use the $each modifier. The following query shows this,
db.users.updateOne(
{ "_id": 1 },
{ $push: { "favorites": { $each: ["mango", "grape"] } } }
)
After executing the above query, the modified document is,
{
"_id": 1,
"name": "John",
"favorites": ["apple", "banana", "orange", "mango", "grape"]
}
3. Appending multiple values to an array in the nested/embedded document:
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.
Syntax:
db.contributor.update({name: "Sumit"}, {$push: {"personal.semesterMarks": {$each: [89, 76.4]}}})
List of $push Operator Modifiers in MongoDB
The $push operator in MongoDB appends a value to an array field. It can be enhanced with several modifiers to customize the behavior when adding elements. Below are the main modifiers:
- $each:
Appends multiple values to an array at once. - $slice:
Limits the number of elements in the array after the $push operation. Positive numbers retain the last N elements, and negative numbers retain the first N. - $sort:
Sorts the array elements after the $push operation. Can be in ascending (1) or descending (-1) order. - $position:
Specifies the position in the array where the new values should be inserted. By default, values are appended to the end.
Frequently Asked Questions
Can the $push operator add multiple values to an array at once?
Yes, the $push operator supports the use of the $each modifier, which allows you to add multiple values to an array in a single operation. This is particularly useful when you have an array of values that need to be appended simultaneously.
What happens if the array field does not exist in the document?
If the array field does not exist in the document, the $push operator will create a new array field and add the specified value to it. Subsequent $push operations will continue appending values to the newly created array.
Is it possible to conditionally add values to an array using the $push operator?
Yes, you can conditionally add values to an array using the $push operator in combination with other modifiers. For example, you can use the $each and $slice modifiers to add values based on certain conditions and limit the size of the array. This provides flexibility in selectively appending elements based on specific criteria.
Are there any limitations to the $push operator in MongoDB?
While the $push operator is powerful for adding elements to arrays, it's important to note that it cannot be used to update other types of fields or perform complex array transformations. For more advanced array manipulations, MongoDB provides additional update operators like $addToSet and $pull.
Conclusion
In summary, the $push operator in MongoDB allows you to add elements to an array field within a document. It appends new values to the end of the array, expanding it with additional data. The $push operator provides a convenient way to manage arrays and is useful for various use cases such as tracking user activities, managing comments, implementing notifications, and more. It can be combined with other operators like $each, $slice, and $position for advanced array updates, enabling you to add multiple values, limit array size, and control the insertion point. Understanding and utilizing the $push operator empowers you to efficiently manipulate arrays in MongoDB, enhancing the functionality and performance of your applications.