Introduction to MongoDB $push Operator
The $push operator is an update operator in MongoDB used to append one or multiple values to the end of an array.
Syntax
{ $push: { <field1>: <value1>, ... } }
Use Cases
The $push operator is used when one or more values need to be added to an existing array within a document.
Example
Assuming there is a collection named users with the following documents:
> db.users.find()
{ "_id" : ObjectId("61fe47557dc8d97c21e492b0"), "name" : "Alice", "scores" : [ 80, 85, 90 ] }
{ "_id" : ObjectId("61fe47557dc8d97c21e492b1"), "name" : "Bob", "scores" : [ 75, 85 ] }
The following example adds a new element to the scores array:
> db.users.updateOne({ name: "Alice" }, { $push: { scores: 95 } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
After executing the update operation above, the contents of the users collection are as follows:
> db.users.find()
{ "_id" : ObjectId("61fe47557dc8d97c21e492b0"), "name" : "Alice", "scores" : [ 80, 85, 90, 95 ] }
{ "_id" : ObjectId("61fe47557dc8d97c21e492b1"), "name" : "Bob", "scores" : [ 75, 85 ] }
The following example adds multiple elements to the scores array:
> db.users.updateOne({ name: "Bob" }, { $push: { scores: { $each: [ 80, 90, 95 ] } } })
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
After executing the update operation above, the contents of the users collection are as follows:
> db.users.find()
{ "_id" : ObjectId("61fe47557dc8d97c21e492b0"), "name" : "Alice", "scores" : [ 80, 85, 90, 95 ] }
{ "_id" : ObjectId("61fe47557dc8d97c21e492b1"), "name" : "Bob", "scores" : [ 75, 85, 80, 90, 95 ] }
Conclusion
The $push operator is an update operator in MongoDB used to append one or multiple values to the end of an array. Multiple elements can be added to the array by using the $each option during the update operation.