TExcelTAD
Home › MongoDB › Querying Arrays

Querying Arrays

Arrays are everywhere in MongoDB documents: the sample store has tags (strings), interests (strings) and items (embedded documents). MongoDB has special rules and operators for querying them.

A single value matches any element

As you saw in Find, a plain value matches if any element equals it, and a comparison operator matches if any element satisfies it:

mongosh · try it yourself
print(db.products.find({ tags: 'single-origin' }).toArray().map(p => p.name));
print(db.orders.find({ 'items.qty': { $gte: 4 } }).toArray().map(o => o._id));
[ 'Ethiopia Yirgacheffe', 'Colombia Supremo' ]
[ 1002, 1009, 1017 ]

Exact array match

If the value is itself an array, the field must equal it exactly, same elements in the same order:

mongosh · try it yourself
print(db.products.find({ tags: ['sweet', 'vegan'] }).toArray().map(p => p.name));
print(db.products.find({ tags: ['vegan', 'sweet'] }).toArray().map(p => p.name));
[ 'Dark Chocolate Bar' ]
[]

Order matters, and so do extra elements: Oat Cookies has ['sweet', 'vegan', 'gluten-free'], so it doesn't match.

$all: contains every value

$all checks that the array contains all of the given values, in any order, with others allowed:

mongosh · try it yourself
print(db.products.find({ tags: { $all: ['vegan', 'sweet'] } }).toArray().map(p => p.name));
print(db.customers.find({ interests: { $all: ['coffee', 'tea'] } }).toArray().map(c => c.name));
[ 'Dark Chocolate Bar', 'Oat Cookies' ]
[ 'Margaret Hamilton', 'Katherine Johnson' ]

$size: array length

$size matches arrays with exactly that many elements. It doesn't accept ranges, so for "more than 2" use $expr with the $size expression, or check whether a position exists:

mongosh · try it yourself
print(db.customers.find({ interests: { $size: 0 } }).toArray().map(c => c.name));
print(db.orders.find({ items: { $size: 3 } }).toArray().map(o => o._id));
print(db.products.find({ 'tags.2': { $exists: true } }).toArray().map(p => p.name));
[ 'Linus Torvalds', 'Radia Perlman' ]
[ 1005 ]
[
  'Ethiopia Yirgacheffe',
  'Colombia Supremo',
  'Decaf Night Owl',
  'Chamomile Calm',
  'Masala Chai',
  'Oat Cookies'
]

'tags.2' is the third element (positions start at 0), so the last line finds products with at least three tags.

$elemMatch: one element must satisfy all conditions

This is the most important array rule. With several conditions on fields of an array of documents, a normal filter lets different elements satisfy different conditions. $elemMatch requires a single element to satisfy all of them:

mongosh · try it yourself
// Some item has productId 15, and some item (maybe another one) has qty >= 2
print(db.orders.find({ 'items.productId': 15, 'items.qty': { $gte: 2 } }).toArray().map(o => o._id));
// One and the same item has productId 15 AND qty >= 2
print(db.orders.find({ items: { $elemMatch: { productId: 15, qty: { $gte: 2 } } } }).toArray().map(o => o._id));
[ 1001, 1005, 1012 ]
[ 1005 ]

Product 15 is the pack of paper filters. Orders 1001 and 1012 each contain one pack of filters plus some other item bought twice, so they satisfy the first query: one item has productId: 15, another has qty: 2. Only order 1005 really contains two packs of filters, and only $elemMatch gets that right.

$elemMatch also works on arrays of plain values, to apply a range to one element:

mongosh · try it yourself
db.scores.insertMany([
  { _id: 'mia', results: [55, 91] },
  { _id: 'leo', results: [72, 78] },
  { _id: 'ava', results: [65, 40] }
]);
// Some element > 60 and some element < 70 (can be two different elements)
print(db.scores.find({ results: { $gt: 60, $lt: 70 } }).toArray().map(s => s._id));
// One element between 60 and 70
print(db.scores.find({ results: { $elemMatch: { $gt: 60, $lt: 70 } } }).toArray().map(s => s._id));
[ 'mia', 'ava' ]
[ 'ava' ]

Mia matches the first query because 91 is greater than 60 and 55 is less than 70, even though none of her scores lies between 60 and 70. Only Ava has such a score (65).

Quick reference

Goal Filter
contains a value { tags: 'vegan' }
contains any of these { tags: { $in: ['vegan', 'nuts'] } }
contains all of these { tags: { $all: ['vegan', 'sweet'] } }
exactly this array { tags: ['sweet', 'vegan'] }
exactly n elements { tags: { $size: 2 } }
one element satisfies several conditions { items: { $elemMatch: { … } } }
element at a position { 'tags.0': 'dark' }

Test yourself

Which filter finds products tagged with both 'brewing' and 'electric', in any order?

  1. { tags: ['brewing', 'electric'] }
  2. { tags: { $all: ['brewing', 'electric'] } }
  3. { tags: { $in: ['brewing', 'electric'] } }
  4. { tags: { $size: 2 } }

When do you need $elemMatch?

  1. Whenever you query an array
  2. When several conditions must hold for the same array element
  3. To match an array exactly
  4. To count elements

How do you find documents whose tags array has at least 3 elements?

  1. { tags: { $size: { $gte: 3 } } }
  2. { 'tags.2': { $exists: true } }
  3. { tags: { $gte: 3 } }
  4. { 'tags.3': { $exists: true } }