"Mastering the Mongo Shell",
# CHAPTER 6
Inserting Documents in MongoDB
1. Introduction
A database is fundamentally a digital filing cabinet. The most important action you can take is putting a file into that cabinet. This is the C in CRUD (Create). In MongoDB, creating data is radically simpler than in SQL. You don't write verboseINSERT INTO ... VALUES statements. You simply hand MongoDB a JSON object, and it handles the rest. In this chapter, we will learn how to write single and multiple documents directly into our collections.
2. Learning Objectives
By the end of this chapter, you will be able to:-
Insert a single document using
insertOne().
-
Insert multiple documents simultaneously using
insertMany().
- Understand the response object returned by MongoDB.
-
Handle automatically generated
idfields.
3. Inserting a Single Document (insertOne())
To add a single record to a collection, we use the insertOne() method. You pass a single JSON object inside the parentheses.
Open the mongosh terminal, ensure you are in a database (e.g., use companydb), and execute:
*Note: In the Mongo Shell, you don't strictly have to put quotes around the keys (like "first_name"), but you DO have to put quotes around string values ("Alice").*
4. The MongoDB Response
When you execute an insert, MongoDB does not just silently succeed. It replies with an acknowledgment object.Why this matters: Because we did not manually provide an _id field in our JSON, MongoDB automatically generated an ObjectId for Alice. The response hands that ID back to us so our frontend application can use it!
5. Inserting Multiple Documents (insertMany())
If an HR admin uploads a spreadsheet of 50 new hires, you do not want to run insertOne() 50 times. Every query requires a network trip to the database, which is slow.
To insert data in bulk, use insertMany(). Instead of passing a single object, you pass an Array of Objects [{}, {}, {}].
*(Notice the Dynamic Schema in action! Charlie has an ismanager field, Diana has an array of skills, and Bob has neither. MongoDB accepts them all into the exact same collection without crashing!)*
6. Providing Your Own id
While 99% of the time you should let MongoDB generate the ObjectId, you are allowed to override it. If you are migrating data from an old MySQL database, you might want to keep the old integer IDs.
DANGER: If you try to insert another document with id: 101, MongoDB will throw a fatal DuplicateKey error and block the insertion. The id must always remain absolutely unique.
7. Mini Project: Populating a Blog
Let's populate aposts collection with structured content.
8. Common Mistakes
-
Syntax Errors with Brackets: The most common beginner mistake with
insertMany()is forgetting the Array brackets[].
db.users.insertMany({name: "A"}, {name: "B"})
*Right:* db.users.insertMany( [ {name: "A"}, {name: "B"} ] )
-
Using legacy commands: Older MongoDB tutorials might tell you to use
db.collection.insert(). This was deprecated in modern MongoDB because it was confusing. Always explicitly useinsertOne()orinsertMany().
9. Best Practices
-
Ordered vs Unordered Inserts: By default,
insertMany()executes in order. If document #3 triggers a Duplicate Key error, MongoDB crashes and stops, meaning documents #4 and #5 are never inserted. If you pass an option{ ordered: false }, MongoDB will try to insert everything, skip the errors, and continue inserting the rest!
10. Exercises
-
1.
Write the command to insert a single document into a
moviescollection with the title "The Matrix" and a year of 1999.
-
2.
What JavaScript array syntax is required when passing data into the
insertMany()method?
11. MongoDB Challenges
Write a singleinsertMany() command to insert two products into the inventory collection. Both products should have a name, price, and a nested object called dimensions containing height and width.
12. MCQ Quiz with Answers
What is the primary architectural advantage of using insertMany() instead of running a for loop that executes insertOne() 100 times?
If you execute an insertOne() command but do NOT explicitly provide an id field in your JSON object, what does MongoDB do?
13. Interview Questions
-
Q: Explain the difference between
insertOne()andinsertMany(). Why is the Array syntax[]strictly required forinsertMany()?
-
Q: If you execute an
insertMany()command containing 1,000 documents, and document #500 contains a duplicateidthat violates a unique constraint, what happens to the batch by default? How can you alter this behavior?
14. FAQs
Q: Is there a limit to how many documents I can pass intoinsertMany()?
A: The only limit is the maximum BSON payload size for a single network request, which is 48 Megabytes. If you try to insert 10 million documents at once, the driver will automatically split it into smaller batches of 100,000 behind the scenes.
15. Summary
You have officially written data to the hard drive. By masteringinsertOne() for individual user actions (like a registration form) and insertMany() for massive administrative data imports, you can populate MongoDB collections rapidly while leveraging the flexibility of dynamic BSON schemas.
16. Next Chapter Recommendation
Now that our collections are filled with thousands of employees and products, we need to know how to retrieve them. In Chapter 7: Finding and Querying Documents, we will master thefind() command to search, filter, and extract precise intelligence from our database.