Array of embedded documents queries in MongoDB - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
When querying arrays inside documents in MongoDB, it's important to know how the query time changes as the data grows.
We want to understand how the number of operations grows when searching embedded arrays.
Analyze the time complexity of the following MongoDB query.
db.orders.find({
items: { $elemMatch: { productId: 123, quantity: { $gt: 2 } } }
})
.limit(5)
This query searches for orders where the items array has at least one element with productId 123 and quantity greater than 2, returning up to 5 results.
Look for repeated checks inside the array of embedded documents.
- Primary operation: Scanning each document's items array to check each embedded document for matching conditions.
- How many times: For each order document, the query examines each item in the items array until it finds a match or reaches the end.
As the number of orders and the size of each items array grow, the query checks more embedded documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 orders with 5 items each | Up to 50 item checks |
| 100 orders with 10 items each | Up to 1,000 item checks |
| 1,000 orders with 20 items each | Up to 20,000 item checks |
Pattern observation: The total checks grow roughly with the number of orders times the average number of items per order.
Time Complexity: O(n * m)
This means the query time grows proportionally with the number of documents (n) times the average size of the embedded array (m).
[X] Wrong: "The query only checks one item per document, so it runs in O(n)."
[OK] Correct: The query must check each item in the array until it finds a match, so it depends on the array size too, making it O(n * m).
Understanding how queries on embedded arrays scale helps you design efficient data models and write performant queries, a valuable skill in real projects.
What if we added an index on the embedded document fields? How would the time complexity change?
Practice
Which MongoDB query operator is used to match documents where at least one element in an array of embedded documents meets multiple conditions?
Solution
Step 1: Understand the need for multiple conditions on one embedded document
When querying arrays of embedded documents, multiple conditions on the same element require a special operator.Step 2: Identify the correct operator for matching multiple conditions on one element
$elemMatch matches documents where at least one array element satisfies all specified conditions.Final Answer:
$elemMatch -> Option DQuick Check:
Multiple conditions on one embedded doc = $elemMatch [OK]
- Using $all which matches all elements separately
- Using $in which matches any value but not multiple conditions
- Confusing $exists with array element matching
Which of the following is the correct MongoDB query syntax to find documents where the comments array contains an embedded document with author equal to "Alice"?
{ comments: { ? } }Solution
Step 1: Identify simple query for matching one field in embedded documents
To find documents where any embedded document in an array has a field equal to a value, use $elemMatch or direct matching.Step 2: Recognize that { comments: { $elemMatch: { author: "Alice" } } } matches if any embedded document has author "Alice"
This syntax matches documents where at least one element in comments array has author "Alice".Final Answer:
{ $elemMatch: { author: "Alice" } } -> Option CQuick Check:
Use $elemMatch for embedded document match [OK]
- Using $in or $all incorrectly with embedded documents
- Confusing array field with embedded document field
- Using direct object without $elemMatch may not always work as expected
Given the collection posts with documents like:
{ _id: 1, comments: [ { author: "Bob", likes: 5 }, { author: "Alice", likes: 3 } ] }What will the query db.posts.find({ comments: { $elemMatch: { author: "Alice", likes: { $gt: 2 } } } }) return?
Solution
Step 1: Understand $elemMatch with multiple conditions
The query looks for documents where at least one comment has author "Alice" and likes greater than 2.Step 2: Check the example document for matching embedded document
The second comment has author "Alice" and likes 3, which is greater than 2, so it matches.Final Answer:
[{ _id: 1, comments: [...] }] -> Option AQuick Check:
Matching embedded doc with $elemMatch returns document [OK]
- Assuming $elemMatch matches separate elements for each condition
- Expecting empty result when conditions are met
- Confusing $elemMatch with $all
Identify the error in this MongoDB query to find documents where reviews array has an embedded document with rating greater than 4 and verified true:
db.collection.find({ reviews: { rating: { $gt: 4 }, verified: true } })Solution
Step 1: Recognize multiple conditions on one embedded document
Multiple conditions on fields inside an array element require $elemMatch to ensure they apply to the same element.Step 2: Identify missing $elemMatch usage
The query incorrectly tries to match multiple fields directly inside the array field, which matches documents with separate elements for each condition, not the same element.Final Answer:
Missing $elemMatch to combine multiple conditions on one embedded document -> Option BQuick Check:
Multiple conditions on one element need $elemMatch [OK]
- Omitting $elemMatch for multiple conditions
- Assuming direct object matches all conditions on one element
- Misunderstanding array query behavior
You have a collection orders with documents like:
{ _id: 1, items: [ { product: "Pen", qty: 10 }, { product: "Notebook", qty: 5 } ] }Write a query to find orders where items contains a product "Pen" with quantity at least 10, and also a product "Notebook" with quantity at least 5.
Which query correctly finds such orders?
Solution
Step 1: Understand the need to match two different embedded documents in the array
We want orders where items array has one element matching Pen with qty >= 10 and another element matching Notebook with qty >= 5.Step 2: Use repeated array field with $elemMatch to require both conditions on separate elements
Repeating the array field key with $elemMatch for each condition ensures at least one array element satisfies each set of conditions.Step 3: Eliminate incorrect options
{ items: { $elemMatch: { product: "Pen", qty: { $gte: 10 }, product: "Notebook", qty: { $gte: 5 } } } } tries to match both products in one element (impossible). { items: { product: "Pen", qty: { $gte: 10 }, product: "Notebook", qty: { $gte: 5 } } } is invalid syntax. { items: { $in: [ { product: "Pen", qty: { $gte: 10 } }, { product: "Notebook", qty: { $gte: 5 } } ] } } uses $in which matches any element but not both conditions.Final Answer:
{ items: { $elemMatch: { product: "Pen", qty: { $gte: 10 } } }, items: { $elemMatch: { product: "Notebook", qty: { $gte: 5 } } } } -> Option AQuick Check:
Repeated field + $elemMatch for multiple different embedded docs [OK]
- Trying to match multiple products in one embedded document
- Using $elemMatch alone for multiple different elements
- Using $in which matches any but not all conditions
