querydrill

Learn ›MongoDB fundamentals ›Nested objects and arrays

$elemMatch and the multi-condition trap

arraysfind()$elemMatch

This is the single most common MongoDB mistake, and it is a favourite interview question because the wrong query still returns results. Two conditions on the same array path are not required to be satisfied by the same element.

Consider:

db.users.find({
  "orders.product": "Laptop",
  "orders.status": "completed"
})

You might think this means:

Find a user having an order where product is Laptop AND status is completed.

Not necessarily.

MongoDB can match:

[
  {
    product: "Laptop",
    status: "pending"
  },
  {
    product: "Mouse",
    status: "completed"
  }
]

Because one array element satisfies:

product = Laptop

And another satisfies:

status = completed

Correct: $elemMatch

db.users.find({
  orders: {
    $elemMatch: {
      product: "Laptop",
      status: "completed"
    }
  }
})

Now MongoDB ensures:

THE SAME ARRAY ELEMENT

product = Laptop
AND
status = completed

This is a very common interview question.

Remember:

Multiple conditions that must apply to the same array object → $elemMatch.

Practise this

1 exercise