insertMany method in MongoDB - Time & Space Complexity
When adding many documents to a MongoDB collection, it's important to understand how the time taken grows as you add more items.
We want to know: How does the cost of inserting many documents change when the number of documents increases?
Analyze the time complexity of the following code snippet.
db.collection.insertMany([
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Carol", age: 27 }
])
This code inserts multiple documents into a MongoDB collection in one operation.
- Primary operation: Inserting each document one by one inside the batch.
- How many times: Once for each document in the input array.
As you add more documents, the total work grows roughly in direct proportion to the number of documents.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 insert actions |
| 100 | About 100 insert actions |
| 1000 | About 1000 insert actions |
Pattern observation: Doubling the number of documents roughly doubles the work.
Time Complexity: O(n)
This means the time to insert documents grows linearly with the number of documents you add.
[X] Wrong: "insertMany inserts all documents instantly, so time does not grow with more documents."
[OK] Correct: Even though insertMany sends documents in one call, the database still processes each document, so more documents mean more work and more time.
Understanding how batch inserts scale helps you explain database performance clearly and shows you know how operations grow with data size.
What if we changed insertMany to insert documents one by one with separate insertOne calls? How would the time complexity change?