← Back to MongoDB Course | Chapter 6: Query Operators | Lesson 4 of 7

Array operators ($all $elemMatch $size)

Array operators query the contents and size of array fields.
Syntax
javascript
{ 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)

bash
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
  1. Expecting separate conditions to bind to one element
  2. Using $size with ranges
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.