Array Operators
Array Operators: free step-by-step lesson with examples, common mistakes, and interview tips — part of MongoDB Tutorial on Toolliyo Academy.
On this page
MongoDB Tutorial · Lesson 23 of 100
Array Operators
Foundations & CRUD ✓ → Queries & Schema → Aggregation & Scale → Atlas & Projects
Queries & Schema · 2 — Design · ~6 min · MongoDB — Query Operators
What is this?
Array operators query lists inside documents: $all, $elemMatch, $size, and equality on array fields. $elemMatch is critical when one array element must satisfy multiple conditions.
Why should you care?
Orders have line items, users have roles[], products have tags[]. Without array operators you get false matches across different elements.
See it live — copy this example
Open mongosh or MongoDB Compass, select database nosqlverse, then run the example. Change one field and run again.
db.orders.insertMany([
{ _id: 1, items: [ { sku: "A", qty: 1 }, { sku: "B", qty: 5 } ] },
{ _id: 2, items: [ { sku: "A", qty: 5 }, { sku: "C", qty: 1 } ] }
])
db.orders.find({ items: { $elemMatch: { sku: "A", qty: { $gte: 5 } } } })
db.orders.find({ "items.sku": { $all: ["A", "B"] } })
db.orders.find({ items: { $size: 2 } })
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- $elemMatch requires the same element sku A and qty ≥ 5 — only order 2.
- $all requires both skus A and B present — order 1.
- $size: 2 matches both sample orders.
Practice next
- Insert the two orders.
- Run the $elemMatch query.
- Contrast with { "items.sku": "A", "items.qty": { $gte: 5 } } without $elemMatch — see the false positive on order 1.
- Find orders that contain sku B.
- Add $elemMatch qty: { $lte: 1 }.
Remember
$elemMatch scopes conditions to one array element. $all requires every listed value. $size checks exact array length.
Cart contains a SKU with quantity
Warehouse picks orders where one line is sku A with qty ≥ 5 for bulk packing.
Outcome: $elemMatch prevents matching qty from a different line item.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!