Skip to main content
MongoDB
CHAPTER 06 Beginner

"Mastering the Mongo Shell",

Updated: May 16, 2026
15 min read

# 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 verbose INSERT 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 id fields.

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:

javascript
123456
db.employees.insertOne({
    first_name: "Alice",
    department: "Engineering",
    salary: 95000,
    skills: ["JavaScript", "Python", "MongoDB"]
})

*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.
javascript
12345
// The response to the query above:
{
  acknowledged: true,
  insertedId: ObjectId("650a2b9f8f1b2c3d4e5f6a7b")
}

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 [{}, {}, {}].
javascript
12345678910111213141516171819
db.employees.insertMany([
    {
        first_name: "Bob",
        department: "Sales",
        salary: 60000
    },
    {
        first_name: "Charlie",
        department: "HR",
        salary: 55000,
        is_manager: true
    },
    {
        first_name: "Diana",
        department: "Engineering",
        salary: 105000,
        skills: ["C++", "System Design"]
    }
])

*(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.
javascript
12345
db.products.insertOne({
    _id: 101, // Forcing a manual ID
    name: "Mechanical Keyboard",
    price: 120
})

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 a posts collection with structured content.
javascript
123456789101112131415161718
use blog_db

db.posts.insertMany([
    {
        title: "Why NoSQL is Awesome",
        author: "TechGuru",
        views: 1500,
        published_at: new Date(),
        tags: ["nosql", "mongodb", "database"]
    },
    {
        title: "Mastering the Mongo Shell",
        author: "DataNinja",
        views: 320,
        published_at: new Date(),
        tags: ["terminal", "tutorial"]
    }
])

8. Common Mistakes

  • Syntax Errors with Brackets: The most common beginner mistake with insertMany() is forgetting the Array brackets [].
*Wrong:* 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 use insertOne() or insertMany().

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. 1. Write the command to insert a single document into a movies collection with the title "The Matrix" and a year of 1999.
  1. 2. What JavaScript array syntax is required when passing data into the insertMany() method?

11. MongoDB Challenges

Write a single insertMany() 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.
javascript
1234
db.inventory.insertMany([
  { name: "Box", price: 5, dimensions: { height: 10, width: 10 } },
  { name: "Tube", price: 8, dimensions: { height: 20, width: 5 } }
])

12. MCQ Quiz with Answers

Question 1

What is the primary architectural advantage of using insertMany() instead of running a for loop that executes insertOne() 100 times?

Question 2

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() and insertMany(). Why is the Array syntax [] strictly required for insertMany()?
  • Q: If you execute an insertMany() command containing 1,000 documents, and document #500 contains a duplicate id that 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 into insertMany()? 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 mastering insertOne() 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 the find() command to search, filter, and extract precise intelligence from our database.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·