Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 70 ยท CRUD: create and read

Querying Nested Fields and Arrays

Learn to query nested documents and arrays in MongoDB: dot notation, matching array elements, positions, exact array matches and arrays of subdocuments.

Real documents are rarely flat. A user has an address object, a product has a list of tags, an order has an array of line items. MongoDB lets you query inside all of these without any special syntax beyond one idea: dot notation. You write the path to the field as a string, with a dot between each level.

In this lesson you will query nested documents, match values inside arrays, target an array position, compare whole arrays, and search arrays of subdocuments. The last topic has a well-known pitfall that is solved by $elemMatch, which gets its own lesson in Array Query Operators. Filters in general are introduced in Finding Documents.

The mongosh listings are real MongoDB commands and are read-only. The runnable examples use the JavaScript practice engine from The Practice Engine Used in This Tutorial, which resolves dot paths and array matching the way MongoDB does for the cases shown here. It is a stand-in, not a database.

Four things to remember

Dot notation "address.city" reaches into a subdocument.
Array contains { tags: "red" } matches if any element is "red".
Position "tags.0" is the first element.
Exact match A whole array or object must match completely.
1 / 2

Dot notation for nested documents

Suppose each customer document looks like this:

JavaScript
{
  _id: 1,
  name: "Mia",
  address: { city: "Oslo", zip: "0150", country: "NO" }
}

To find customers in Oslo, give the path as a quoted string:

JavaScript
db.customers.find({ "address.city": "Oslo" })

The quotes are required because address.city is not a valid JavaScript identifier. Dot paths can be as deep as the document, such as "stats.2024.total", and they work almost everywhere you name a field: filters, projections, sorts and updates.

Matching a whole subdocument

You can also compare against a complete nested document:

JavaScript
db.customers.find({ address: { city: "Oslo", zip: "0150", country: "NO" } })

This is an exact match. The subdocument must have exactly these fields, with these values, in this order. A document whose address has an extra field, or the same fields in a different order, does not match. Because of that fragility, dot notation is almost always the better choice. Use it for one field or several: { "address.city": "Oslo", "address.country": "NO" } ignores extra fields and field order.

Matching values inside arrays

Take a product with a tags array:

JavaScript
{ _id: 1, name: "Desk Lamp", tags: ["lighting", "office", "led"] }

Querying an array field with a plain value means "the array contains this value":

JavaScript
db.products.find({ tags: "office" })

That matches the lamp, and any other document where at least one element of tags equals "office". You do not need a special operator for this common case.

Matching the exact array

If the filter value is itself an array, MongoDB compares the whole array: same elements, same number, same order.

JavaScript
db.products.find({ tags: ["lighting", "office", "led"] })   // matches
db.products.find({ tags: ["office", "lighting", "led"] })   // does not match: order differs
db.products.find({ tags: ["lighting", "office"] })          // does not match: shorter

When you want "contains all of these in any order", use $all, and for the length of an array use $size; both are in Array Query Operators.

Matching by position

Dot notation also takes an array index, starting at 0:

JavaScript
db.products.find({ "tags.0": "lighting" })     // first tag is "lighting"
db.products.find({ "tags.1": "office" })       // second tag is "office"

Use it only when position carries meaning, for example when the first element is the primary category. Position queries cannot use a normal index as effectively as plain element queries, so do not use them as a general search tool.

JS Nested fields and simple arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The whole-subdocument filter finds only Mia. Lena has the same values but in another order (zip before city), and Sam has an extra floor field. The two dot-notation filters ignore those differences. Likewise the exact array ["vip", "newsletter"] matches only Mia, because Lena's tags are in the opposite order.

Arrays of subdocuments

An order usually stores its line items as an array of small documents:

JavaScript
{
  _id: 100,
  customer: "Mia",
  items: [
    { sku: "A1", qty: 2, price: 9.5 },
    { sku: "B7", qty: 10, price: 3 }
  ]
}

Dot notation walks through the array automatically. A path such as "items.sku" looks at the sku of every element:

JavaScript
db.orders.find({ "items.sku": "B7" })              // some item has sku B7
db.orders.find({ "items.qty": { $gt: 5 } })        // some item has qty above 5
db.orders.find({ "items.0.sku": "A1" })            // the first item has sku A1

The trap: conditions on different elements

What if you want orders that contain item A1 with a quantity greater than 5? It looks natural to write:

JavaScript
db.orders.find({ "items.sku": "A1", "items.qty": { $gt: 5 } })

This does not mean "one item that is A1 and has more than five units". Each condition is checked separately against the whole array, so the order above matches: one element (A1) satisfies the first condition and a different element (B7, with quantity 10) satisfies the second. The query is true even though no single item meets both.

The fix is $elemMatch, which requires that one array element satisfies all its conditions together:

JavaScript
db.orders.find({ items: { $elemMatch: { sku: "A1", qty: { $gt: 5 } } } })

Whenever a condition involves two or more fields of the same subdocument in an array, use $elemMatch. For one field only, dot notation is enough.

JS Arrays of subdocuments and the $elemMatch fix

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Order 100 shows up with the separate conditions (A1 from the first item, a quantity above 5 from the second item) but not with $elemMatch. Only Omar's order really has one item that is both A1 and above five.

Quick reference

You want Filter
Field inside a subdocument { "address.city": "Oslo" }
Whole subdocument, exactly { address: { city: "Oslo", zip: "0150" } }
Array contains a value { tags: "vip" }
Array equals exactly { tags: ["vip", "newsletter"] }
Element at a position { "tags.0": "vip" }
Field of some subdocument in an array { "items.sku": "A1" }
One element meets several conditions { items: { $elemMatch: { ... } } }

Keep in mind that deep nesting and large arrays have costs. Each time you reach into an array, MongoDB looks at its elements, and arrays that keep growing become a problem of their own; see Embedding vs Referencing for how to decide what to embed.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which filter finds customers whose address document has city equal to Oslo, whatever other fields the address contains?

    A dot path in quotes reaches into the subdocument and ignores the other fields. The first option is an exact subdocument match and would require address to be exactly { city: 'Oslo' }. The second is not valid JavaScript without quotes.
  2. 2. A document has tags: ['red', 'blue']. Which filter matches it?

    A plain value matches when the array contains it. A filter array must equal the whole array in the same order, and 'tags.2' would be a third element that does not exist.
  3. 3. What does { 'items.sku': 'A1', 'items.qty': { $gt: 5 } } guarantee?

    Each condition is checked against the array on its own. Use $elemMatch when one element must satisfy all of the conditions.
  4. 4. Which filter matches documents where the first element of tags is 'vip'?

    In dot notation the array index is a path segment, starting at 0. Square brackets are not part of the syntax.

Summary

  • Dot notation with a quoted path ("address.city") queries nested fields, and ignores extra fields and field order.
  • Comparing a whole subdocument is an exact match, including field order, so it is fragile.
  • A plain value against an array field means "contains"; an array value must equal the whole array in order.
  • "tags.0" targets an array position; "items.sku" looks at that field in every element of an array of subdocuments.
  • Several conditions on array-of-subdocument paths can be met by different elements; use $elemMatch when one element must meet them all.

Next, learn the operators that build richer conditions, starting with Comparison Operators.