One-to-one embedding pattern in MongoDB - Time & Space Complexity
When using one-to-one embedding in MongoDB, we want to know how the time to get data changes as the data grows.
We ask: How does fetching a document with embedded data scale when the number of documents increases?
Analyze the time complexity of the following MongoDB query.
// Find a user and get their profile embedded inside
db.users.findOne({ _id: userId })
This query fetches one user document that includes an embedded profile document inside it.
Look for repeated steps in the query process.
- Primary operation: Searching the users collection for one document by _id.
- How many times: This happens once per query, no loops or repeated scans.
As the number of users grows, how does the time to find one user change?
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Few operations, quick lookup |
| 100 | Still very quick, almost same time |
| 1000 | Lookup time stays about the same |
Pattern observation: Because the query uses a unique _id index, the time stays almost constant no matter how many users there are.
Time Complexity: O(1)
This means fetching one user with embedded data takes about the same time no matter how many users exist.
[X] Wrong: "Fetching embedded data gets slower as the collection grows because it has to look through all documents."
[OK] Correct: The query uses a unique _id index, so it directly finds the document without scanning all documents.
Understanding how embedding affects query speed helps you design fast and simple data models, a skill valued in real projects and interviews.
"What if the embedded document was stored in a separate collection and you needed to join it? How would the time complexity change?"