Skip to content

Arrays & Nested Documents

$all

Require several values to be present in an array, regardless of order.

IntermediateAbout 4 minutes

$all means the array contains every value in the list. Order does not matter. Extra values are fine. It is 'must have these', not 'equals this list'.

db.users.find({
  skills: { $all: ["Node.js", "MongoDB"] }
})
Rahul has both skills, in any order, maybe more
{ name: "Rahul", skills: ["Node.js", "MongoDB"] }
// also matches ["MongoDB", "Express", "Node.js"]

$all

  • Every listed value is in the array
  • Order ignored
  • Superset is OK

$in / exact equality

  • $in — at least one overlap
  • Exact — whole array equals the list, order matters
db.orders.find({
  items: {
    $all: [
      { $elemMatch: { name: "Mechanical Keyboard" } },
      { $elemMatch: { name: "USB-C Cable" } }
    ]
  }
})
Both products on the same order — $all of $elemMatch

That last shape is 'the array contains a match for A and a match for B'. You will not write it every day. For scalars, $all is enough.

Interview question

What is the difference between $all and $in on an array field?

Think about it first.