MongoDB Arrays
What Is Arrays?
A MongoDB field can hold an array of scalars or of embedded documents. Querying an array field with a plain value matches if any element equals it. When you need several conditions to hold on the same array element, use $elemMatch. Updating arrays uses operators such as $push, $pull, $addToSet, and the positional operators $ and $[<identifier>].
Why It Matters
| Reason | Benefit |
|---|---|
| Natural for lists | Tags, phone numbers, and line items fit as arrays without extra tables. |
| Precise element matching | $elemMatch avoids false matches across different elements. |
| In-place edits | Positional operators and arrayFilters update one element without rewriting the array. |
| Fast lookups | Multikey indexes make queries on array elements efficient. |
How To Use It
- Insert documents with a tags array and an items array of subdocuments.
- Query an element with find({ tags: "mongodb" }).
- Require several tags with $all and a specific length with $size.
- Use $elemMatch on items to match both qty and price in the same element.
- Append and remove elements with $push and $pull.
- Update one element with the positional $ operator.
- Update many matching elements with $[x] and arrayFilters.
- Create an index on the array field and inspect it with explain().
mongosh Examples
db.orders.insertMany([
{ _id: 1, tags: ["db", "mongodb"], items: [{ sku: "A", qty: 2, price: 10 }, { sku: "B", qty: 1, price: 50 }] },
{ _id: 2, tags: ["web"], items: [{ sku: "A", qty: 5, price: 10 }] }
])
// Any element equals
db.orders.find({ tags: "mongodb" })
// Contains all, and by size
db.orders.find({ tags: { $all: ["db", "mongodb"] } })
db.orders.find({ tags: { $size: 1 } })
// Same element must satisfy both conditions
db.orders.find({ items: { $elemMatch: { sku: "A", qty: { $gte: 5 } } } })
// Updates
db.orders.updateOne({ _id: 1 }, { $push: { tags: "tutorial" } })
db.orders.updateOne({ _id: 1 }, { $pull: { tags: "db" } })
// Positional: first matching element
db.orders.updateOne({ _id: 1, "items.sku": "B" }, { $set: { "items.$.qty": 3 } })
// All matching elements
db.orders.updateMany(
{},
{ $inc: { "items.$[x].price": 1 } },
{ arrayFilters: [{ "x.sku": "A" }] }
)
// Multikey index
db.orders.createIndex({ tags: 1 }) Edge Cases & Pitfalls
Conditions can match different elements
{ "items.sku": "A", "items.qty": 5 } can be satisfied by two separate elements. Use $elemMatch.
Exact array match is strict
{ tags: ["a", "b"] } will not match ["b", "a"] or ["a", "b", "c"]. Use $all to ignore order.
Positional $ updates one element
It affects only the first element matched by the query. Use $[identifier] with arrayFilters for all of them.
Compound multikey limit
A compound index can include at most one array field per document, otherwise inserts fail.
Unbounded arrays
Arrays that grow forever hurt performance and risk the 16 MiB limit. Move them into their own collection.
Cheat Sheet
| Topic | Detail |
|---|---|
| { tags: "db" } | Matches if any element equals "db" |
| { tags: ["a","b"] } | Exact match of the whole array, in order |
| $all | Array contains all listed values, in any order |
| $size | Array has exactly the given length |
| $elemMatch | At least one element satisfies all the given conditions |
| $push / $addToSet | Append an element, optionally only if unique |
| $pull / $pop | Remove matching elements, or the first/last element |
| $ (positional) | Update the first element matched by the query |
| $[identifier] with arrayFilters | Update all elements matching a filter |
| Multikey index | An index on an array field gets one entry per element |
Key Takeaways
Without $elemMatch, separate conditions on an array of documents can be satisfied by different elements. Use $elemMatch when they must match the same element.
Frequently Asked Questions
How do I find documents where an array contains a value?
Query the field with the value directly, such as find({ tags: "mongodb" }). It matches when any element equals it.
When should I use $elemMatch?
When several conditions must be true for the same array element, especially in arrays of embedded documents.
How do I add a value only if it is not already there?
Use $addToSet. $push always appends, even if the value exists.
How do I update every matching array element?
Use the filtered positional operator $[identifier] along with the arrayFilters option in updateOne or updateMany.
What is a multikey index?
When you index an array field, MongoDB creates an index entry for each element. That is a multikey index, and it is created automatically.
How do I remove the last element of an array?
Use $pop with 1 to remove the last element, or -1 to remove the first.
Next: MongoDB Indexes
Continue the MongoDB learning path.
CODETOFUN NEWS
Stay Ahead in Tech
Get the latest IT news, programming updates, and technology trends directly on your phone.
Your daily dose of tech, straight to your feed.
8 people found this page helpful
