0
0
MongodbHow-ToBeginner · 4 min read

How to Find Documents in Nested Arrays in MongoDB

To find documents with specific values inside a nested array in MongoDB, use dot notation to access the nested fields or the $elemMatch operator to match array elements. For example, { 'outerArray.innerArray.field': value } or { outerArray: { $elemMatch: { innerArray: { $elemMatch: { field: value } } } } }.
📐

Syntax

Use dot notation to access fields inside nested arrays. The $elemMatch operator helps match elements inside arrays with specific conditions.

  • Dot notation: { 'outerArray.innerArray.field': value } searches for documents where field inside innerArray inside outerArray equals value.
  • $elemMatch: { outerArray: { $elemMatch: { innerArray: { $elemMatch: { field: value } } } } } matches documents where an element in outerArray contains an element in innerArray with field equal to value.
mongodb
db.collection.find({ 'outerArray.innerArray.field': value })
db.collection.find({
  outerArray: {
    $elemMatch: {
      innerArray: {
        $elemMatch: {
          field: value
        }
      }
    }
  }
})
💻

Example

This example shows how to find documents where a nested array contains an object with a specific field value.

mongodb
db.products.insertMany([
  {
    name: "ProductA",
    categories: [
      {
        type: "electronics",
        tags: [
          { label: "new", priority: 1 },
          { label: "sale", priority: 2 }
        ]
      },
      {
        type: "home",
        tags: [
          { label: "popular", priority: 3 }
        ]
      }
    ]
  },
  {
    name: "ProductB",
    categories: [
      {
        type: "garden",
        tags: [
          { label: "sale", priority: 2 }
        ]
      }
    ]
  }
])

// Find products with a tag label "sale" inside categories

// Using dot notation
 db.products.find({ 'categories.tags.label': 'sale' })

// Using $elemMatch for nested arrays
 db.products.find({
   categories: {
     $elemMatch: {
       tags: {
         $elemMatch: {
           label: 'sale'
         }
       }
     }
   }
 })
Output
[ { "_id": ObjectId("..."), "name": "ProductA", "categories": [ ... ] }, { "_id": ObjectId("..."), "name": "ProductB", "categories": [ ... ] } ]
⚠️

Common Pitfalls

Common mistakes include:

  • Using dot notation without understanding it matches any nested array element, which may return unexpected results.
  • Not using $elemMatch when you need to match multiple conditions inside the same array element.
  • Confusing the structure of nested arrays and fields, leading to incorrect queries.

Example of a wrong query and the correct fix:

mongodb
// Wrong: This matches any category with type 'electronics' and any tag with label 'sale' but not necessarily in the same category
 db.products.find({ 'categories.type': 'electronics', 'categories.tags.label': 'sale' })

// Right: Use $elemMatch to ensure both conditions are in the same category element
 db.products.find({
   categories: {
     $elemMatch: {
       type: 'electronics',
       tags: {
         $elemMatch: { label: 'sale' }
       }
     }
   }
 })
📊

Quick Reference

Tips for querying nested arrays in MongoDB:

  • Use dot notation for simple nested field queries.
  • Use $elemMatch to match multiple conditions inside the same array element.
  • Remember nested arrays require nested $elemMatch operators.
  • Test queries on sample data to confirm correct matches.

Key Takeaways

Use dot notation to query fields inside nested arrays simply.
Use $elemMatch to match multiple conditions within the same nested array element.
Nested arrays require nested $elemMatch operators for precise matching.
Avoid mixing conditions on different array elements without $elemMatch.
Test queries on sample data to ensure they return expected results.