MongoDB Arrays

Intermediate
9 min read
Updated: Nov 2026
Getting Started

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

ReasonBenefit
Natural for listsTags, phone numbers, and line items fit as arrays without extra tables.
Precise element matching$elemMatch avoids false matches across different elements.
In-place editsPositional operators and arrayFilters update one element without rewriting the array.
Fast lookupsMultikey indexes make queries on array elements efficient.

How To Use It

  1. Insert documents with a tags array and an items array of subdocuments.
  2. Query an element with find({ tags: "mongodb" }).
  3. Require several tags with $all and a specific length with $size.
  4. Use $elemMatch on items to match both qty and price in the same element.
  5. Append and remove elements with $push and $pull.
  6. Update one element with the positional $ operator.
  7. Update many matching elements with $[x] and arrayFilters.
  8. Create an index on the array field and inspect it with explain().

mongosh Examples

mongosh
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

TopicDetail
{ tags: "db" }Matches if any element equals "db"
{ tags: ["a","b"] }Exact match of the whole array, in order
$allArray contains all listed values, in any order
$sizeArray has exactly the given length
$elemMatchAt least one element satisfies all the given conditions
$push / $addToSetAppend an element, optionally only if unique
$pull / $popRemove matching elements, or the first/last element
$ (positional)Update the first element matched by the query
$[identifier] with arrayFiltersUpdate all elements matching a filter
Multikey indexAn 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.

MongoDB Indexes →

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.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful