0
0
MongoDBquery~5 mins

$push operator for adding to arrays in MongoDB

Choose your learning style9 modes available
Introduction

The $push operator adds a new item to the end of an array inside a document. It helps you keep lists updated easily.

You want to add a new comment to a list of comments on a blog post.
You need to add a new tag to a list of tags for a product.
You want to add a new score to a list of scores for a player.
You want to keep track of new tasks added to a user's task list.
You want to add a new friend to a user's list of friends.
Syntax
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.

Examples
Adds "painting" to Alice's hobbies array.
MongoDB
db.users.updateOne(
  { name: "Alice" },
  { $push: { hobbies: "painting" } }
)
Adds the number 95 to Bob's scores array.
MongoDB
db.users.updateOne(
  { name: "Bob" },
  { $push: { scores: 95 } }
)
Adds multiple tags "new" and "featured" to Carol's tags array.
MongoDB
db.users.updateOne(
  { name: "Carol" },
  { $push: { tags: { $each: ["new", "featured"] } } }
)
Adds "task1" at the start of Dave's tasks array using $position.
MongoDB
db.users.updateOne(
  { name: "Dave" },
  { $push: { tasks: { $each: ["task1"], $position: 0 } } }
)
Sample Program

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.

MongoDB
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" }))
OutputSuccess
Important Notes

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.

Summary

$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.