Arrays of Documents and $elemMatch

An array can hold documents too. This course has an orders collection. Each order has an array of items, and each item is a small document with a product and a quantity:

db.orders.findOne({ _id: 2 })

Output:

{
  _id: 2,
  customer: 'Ben',
  items: [ { product: 'pen', qty: 1 }, { product: 'notebook', qty: 6 } ]
}

Dot notation works inside arrays. "items.product" looks at the product field of every item in the array:

db.orders.find(
  { "items.product": "pen" },
  { _id: 0, customer: 1 }
)

Output:

[ { customer: 'Asha' }, { customer: 'Ben' } ]

Asha and Ben both have a pen in their order.

Now try two conditions: orders with a pen, where the quantity is 5 or more. The result may surprise you:

db.orders.find(
  { "items.product": "pen", "items.qty": { $gte: 5 } },
  { _id: 0, customer: 1 }
)

Output:

[ { customer: 'Asha' }, { customer: 'Ben' } ]

Ben ordered only 1 pen, but he still matched. Each condition was checked on its own. One item is a pen, and a different item (his 6 notebooks) has a quantity of 5 or more.

To check both conditions on the same item, use $elemMatch:

db.orders.find(
  { items: { $elemMatch: {
    product: "pen",
    qty: { $gte: 5 }
  } } },
  { _id: 0, customer: 1 }
)

Output:

[ { customer: 'Asha' } ]

$elemMatch matches an order only if one item passes every condition inside it. Only Asha has a single item that is a pen with a quantity of 5 or more.

Use dot notation for one condition on an array of documents. When several conditions must be true for the same item, use $elemMatch.

In the exercise, find the orders that have a notebook with a quantity of 3 or more.