0
0
MongodbHow-ToBeginner · 3 min read

How to Add Element to Array in MongoDB: Simple Guide

To add an element to an array in MongoDB, use the $push update operator with updateOne or updateMany. This operator appends the specified value to the array field in the document.
📐

Syntax

The $push operator adds a value to an array field in a document. It is used with update commands like updateOne or updateMany.

  • filter: Selects the document(s) to update.
  • update: Uses { $push: { arrayField: value } } to add value to arrayField.
mongodb
db.collection.updateOne(
  { <filter> },
  { $push: { <arrayField>: <value> } }
)
💻

Example

This example adds the string "apple" to the fruits array of the document where name is "John".

mongodb
db.users.updateOne(
  { name: "John" },
  { $push: { fruits: "apple" } }
)
Output
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
⚠️

Common Pitfalls

1. Using $push on a non-array field: This causes an error because $push only works on arrays.

2. Forgetting the filter: Without a proper filter, you might update the wrong documents or none at all.

3. Using $push instead of $addToSet when you want to avoid duplicates: $push always adds the element, even if it already exists.

mongodb
/* Wrong: pushing to a non-array field */
db.users.updateOne(
  { name: "John" },
  { $push: { age: 30 } }  // 'age' is not an array
)

/* Right: push to an array field */
db.users.updateOne(
  { name: "John" },
  { $push: { fruits: "banana" } }
)
📊

Quick Reference

  • $push: Adds an element to an array.
  • $addToSet: Adds an element only if it does not exist (no duplicates).
  • updateOne(filter, update): Updates one matching document.
  • updateMany(filter, update): Updates all matching documents.

Key Takeaways

Use the $push operator to add elements to arrays in MongoDB documents.
Always specify a filter to target the correct document(s) when updating.
Ensure the target field is an array before using $push to avoid errors.
Use $addToSet instead of $push to prevent duplicate entries in arrays.