The $push operator adds a new item to the end of an array inside a document. It helps you keep lists updated easily.
$push operator for adding to arrays in MongoDB
db.collection.updateOne(
{ <filter> },
{ $push: { <arrayField>: <valueToAdd> } }
)db.collection.updateOne() updates one document matching the filter.
$push adds the valueToAdd to the end of the array in arrayField.
db.users.updateOne(
{ name: "Alice" },
{ $push: { hobbies: "painting" } }
)db.users.updateOne(
{ name: "Bob" },
{ $push: { scores: 95 } }
)db.users.updateOne(
{ name: "Carol" },
{ $push: { tags: { $each: ["new", "featured"] } } }
)$position.db.users.updateOne(
{ name: "Dave" },
{ $push: { tasks: { $each: ["task1"], $position: 0 } } }
)This program creates a user named Emma with two hobbies. Then it adds a new hobby "cycling" to her hobbies array using $push. It prints the document before and after the update to show the change.
use testdb // Insert a sample user document db.users.insertOne({ name: "Emma", hobbies: ["reading", "swimming"] }) // Show document before update print("Before update:") printjson(db.users.findOne({ name: "Emma" })) // Add a new hobby using $push const updateResult = db.users.updateOne( { name: "Emma" }, { $push: { hobbies: "cycling" } } ) // Show update result print("Update result:") printjson(updateResult) // Show document after update print("After update:") printjson(db.users.findOne({ name: "Emma" }))
The $push operation takes O(1) time to add an element at the end of the array.
Use $each with $push to add multiple items at once.
Common mistake: Trying to $push to a field that is not an array will cause an error.
Use $push when you want to add items to an array; use $addToSet if you want to avoid duplicates.
$push adds new items to the end of an array inside a document.
It is useful for updating lists like hobbies, tags, or tasks.
You can add one or many items using $push and $each.