Subset pattern for large documents in MongoDB - Time & Space Complexity
When working with large documents in MongoDB, fetching only needed parts helps save time.
We want to know how the time to get data changes when we ask for just a subset of fields.
Analyze the time complexity of the following MongoDB query using projection.
db.collection.find(
{ status: "active" },
{ name: 1, email: 1, _id: 0 }
).toArray()
This query finds documents with status "active" and returns only the name and email fields.
Look at what repeats as the query runs:
- Primary operation: Scanning documents matching the filter.
- How many times: Once per matching document.
- Projection step: Extracting only requested fields from each document.
- How many times: Also once per matching document.
As the number of matching documents grows, the work grows too.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 document scans + 10 projections |
| 100 | 100 document scans + 100 projections |
| 1000 | 1000 document scans + 1000 projections |
Pattern observation: The total work grows roughly in direct proportion to the number of matching documents.
Time Complexity: O(n)
This means the time to run the query grows linearly with the number of documents that match the filter.
[X] Wrong: "Selecting fewer fields makes the query run in constant time regardless of data size."
[OK] Correct: Even if you ask for fewer fields, MongoDB still scans each matching document once, so time grows with the number of matches.
Understanding how projection affects query time shows you know how to handle big data efficiently and write queries that scale well.
"What if we added an index on the status field? How would that change the time complexity?"
Practice
Solution
Step 1: Understand subset pattern purpose
The subset pattern is used to get only the needed parts of large documents instead of the whole document.Step 2: Identify the benefit
This reduces the amount of data sent over the network and improves performance.Final Answer:
To retrieve only specific fields from documents to reduce data size -> Option AQuick Check:
Subset pattern = retrieve specific fields [OK]
- Thinking it deletes documents
- Confusing with indexing
- Assuming it merges documents
name and age fields from documents in a MongoDB collection named users?Solution
Step 1: Understand find() parameters
The first parameter is the query filter (empty {} means all documents), the second is the projection specifying fields to include.Step 2: Identify correct projection syntax
Using {name: 1, age: 1} includes only these fields in the result.Final Answer:
db.users.find({}, {name: 1, age: 1}) -> Option BQuick Check:
Projection with 1 includes fields [OK]
- Putting projection in the first argument
- Using 0 instead of 1 to include fields
- Omitting the empty filter {}
products with documents containing _id, name, price, and details fields, what will be the output of this query?db.products.find({}, {name: 1, price: 1, _id: 0})Solution
Step 1: Analyze projection fields
The projection includesnameandpricewith 1, and excludes_idwith 0.Step 2: Understand MongoDB default behavior
By default,_idis included unless explicitly excluded. Here it is excluded.Final Answer:
Documents with only name and price fields, excluding _id -> Option AQuick Check:
Projection includes name, price; excludes _id [OK]
- Assuming _id is always included
- Thinking projection excludes all other fields automatically
- Confusing 0 and 1 in projection
title and author fields from books collection:db.books.find({}, {title: 1, author: 0})Why does this query cause an error or unexpected result?
Solution
Step 1: Check projection rules
MongoDB does not allow mixing inclusion (1) and exclusion (0) in the same projection except for _id.Step 2: Identify the problem in given projection
Here,titleis included (1) andauthoris excluded (0), which is invalid.Final Answer:
Mixing inclusion and exclusion in projection causes error -> Option DQuick Check:
Projection must be all include or all exclude except _id [OK]
- Mixing 1 and 0 in projection fields
- Forgetting _id can be excluded separately
- Assuming filter is mandatory for projection
orders with documents containing many fields including customer, items, total, and shipping. You want to fetch only customer and the total fields but exclude _id. Which query correctly applies the subset pattern for best performance?Solution
Step 1: Include needed fields
To get onlycustomerandtotal, set them to 1 in projection.Step 2: Exclude _id field
Set_idto 0 to exclude it from results.Step 3: Avoid mixing inclusion and exclusion
All fields except_idmust be included (1), no mixing with 0.Final Answer:
db.orders.find({}, {customer: 1, total: 1, _id: 0}) -> Option CQuick Check:
Include fields with 1, exclude _id with 0 [OK]
- Including _id by default
- Mixing 1 and 0 in fields other than _id
- Excluding needed fields accidentally
Ready to prove it?
Pass the test and this pattern moves unknown
