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"] }
}){ 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" } }
]
}
})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.
$in: the array shares at least one value with the list. $all: every value in the list appears in the array. A user with only Node.js matches $in: [Node.js, MongoDB] and misses $all.