Array operators ($all $elemMatch $size)
Array operators query the contents and size of array fields.
In this page:
Syntax
{ array_field: { $all: [value1, value2] } }
{ array_field: { $elemMatch: { key: value } } }
{ array_field: { $size: n } }
Array operators ($all $elemMatch $size)
Matching a value in an array field works with plain equality. $all requires several values to be present, $size matches an exact length and $elemMatch requires one element to satisfy several conditions at once.
Without $elemMatch, conditions may be satisfied by different elements.
Note:
Use $elemMatch when multiple conditions must hold for the same array element.
Example: Array operators ($all $elemMatch $size)
test> db.posts.insertMany([
... { _id: 1, tags: ["js", "node", "db"], scores: [{ who: "a", v: 5 }, { who: "b", v: 9 }] },
... { _id: 2, tags: ["js"], scores: [{ who: "a", v: 9 }, { who: "b", v: 1 }] }
... ])
{ acknowledged: true, insertedIds: { '0': 1, '1': 2 } }
test> db.posts.find({ tags: "node" }, { _id: 1 })
[ { _id: 1 } ]
test> db.posts.find({ tags: { $all: ["js", "db"] } }, { _id: 1 })
[ { _id: 1 } ]
test> db.posts.find({ tags: { $size: 1 } }, { _id: 1 })
[ { _id: 2 } ]
test> db.posts.find({ scores: { $elemMatch: { who: "b", v: { $gt: 5 } } } }, { _id: 1 })
[ { _id: 1 } ]
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Expecting separate conditions to bind to one element
- Using $size with ranges
- Forgetting arrays of subdocuments need dotted paths
Chapter Summary
- Equality matches any element
- $all needs every listed value
- $size matches exact length
- $elemMatch binds conditions to one element
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: