$push
The $push operator in Amazon DocumentDB is used to add an item to an array field in a document. This operator is particularly useful when you need to append new data to an existing array without overwriting the entire array.
Parameters
-
field: The name of the array field to which the new element should be added. -
value: The value to be added to the array. -
position: (optional) A modifier that specifies the position in the array where the new element should be added. Supported modifiers include$(add to the end of the array) and$[](add to the end of the array, ignoring any array filters).
Example (MongoDB Shell)
The following example demonstrates how to use the $push operator to add new elements to an array field in a document.
Create sample documents
db.users.insert([ { _id: 1, name: "John Doe", hobbies: ["reading", "swimming"] }, { _id: 2, name: "Jane Smith", hobbies: ["gardening", "cooking"] } ])
Query example
db.users.updateOne( { _id: 1 }, { $push: { hobbies: "hiking" } } )
Output
{
"acknowledged" : true,
"matchedCount" : 1,
"modifiedCount" : 1
}
After running the update, the document with _id: 1 will have the hobbies array updated to ["reading", "swimming", "hiking"].
Code examples
To view a code example for using the $push command, choose the tab for the language that you want to use: