Paramclasses Academy - Blog

Tutorials Details

←
Post 11 of 35
→

MongoDB insertOne() and insertMany() with Practical Examples

MongoDB insertOne() and insertMany() with Practical Examples

November 5, 2026

MongoDB insertOne() and insertMany() with Practical Examples

❖ Welcome to Param Classes!

MongoDB is a popular NoSQL database that stores information in the form of documents. While developing an application, one of the first tasks is adding data to a database.

MongoDB provides two important methods to insert documents into a collection:

  • insertOne() – Inserts a single document.

  • insertMany() – Inserts multiple documents.

Both methods are part of MongoDB's Create operation and are commonly used in applications such as student management systems, e-commerce websites, blogs, and user management platforms.

In this beginner-friendly tutorial by Param Classes, you will learn how to use insertOne() and insertMany() with their syntax, practical examples, expected output, and common mistakes.

✦ 1. What Is Document Insertion in MongoDB?

Document insertion means adding new records to a MongoDB collection.

MongoDB stores data in BSON (Binary JSON) format. Documents look similar to JSON objects and contain field-value pairs.

For example, a student document may look like this:

{
    name: "Rahul",
    age: 21,
    course: "Web Development",
    city: "Raipur"
}

Here:

  • name is a field.

  • "Rahul" is its value.

  • age, course, and city are other fields.

MongoDB allows you to insert one document or multiple documents using different insertion methods.

✦ 2. Prepare Your MongoDB Database

Before inserting documents, make sure MongoDB Server is running and you are connected through MongoDB Shell (mongosh).

Step 1: Open MongoDB Shell

Open your terminal or command prompt and connect to MongoDB using mongosh.

Step 2: Select a Database

use college

This command switches to the college database. If the database does not exist, MongoDB will create it when data is first stored.

Step 3: Check Available Collections

show collections

This command displays the collections available in the selected database.

We will use a collection named students for our examples.

✦ 3. What Is insertOne() in MongoDB?

The insertOne() method is used to insert one document into a MongoDB collection.

It is useful when you want to add a single record, such as one student, one customer, or one product.

Syntax of insertOne()

db.collectionName.insertOne({
    field1: "value1",
    field2: "value2",
    field3: "value3"
})

Explanation:

  • db represents the current database.

  • collectionName is the name of the collection.

  • insertOne() is the method used to insert one document.

  • The document contains field-value pairs.

Practical Example 1: Insert One Student

Let's insert one student record into the students collection.

db.students.insertOne({
    name: "Rahul",
    age: 21,
    course: "Web Development",
    city: "Raipur",
    status: "Active"
})

Expected Output:

{
    acknowledged: true,
    insertedId: ObjectId("...")
}

Explanation:

  • acknowledged: true means MongoDB acknowledged the operation.

  • insertedId contains the unique _id of the inserted document.

MongoDB automatically generates an _id field if you do not provide one.

Practical Example 2: Insert an Employee Record

You can also insert employee information into a collection.

db.employees.insertOne({
    name: "Amit Sharma",
    age: 28,
    department: "IT",
    salary: 35000,
    city: "Raipur"
})

This command inserts one employee document into the employees collection.

Practical Example 3: Insert a Product Record

db.products.insertOne({
    productName: "Laptop",
    brand: "Dell",
    price: 55000,
    stock: 10,
    category: "Electronics"
})

This example inserts one product record into the products collection.

✦ 4. What Is insertMany() in MongoDB?

The insertMany() method is used to insert multiple documents into a collection in a single operation.

It is useful when you want to add several students, customers, employees, or products at the same time.

Syntax of insertMany()

db.collectionName.insertMany([
    {
        field1: "value1",
        field2: "value2"
    },
    {
        field1: "value1",
        field2: "value2"
    }
])

Explanation:

  • db represents the current database.

  • collectionName represents the target collection.

  • insertMany() inserts multiple documents.

  • Square brackets [] contain the array of documents.

  • Each document is written inside curly brackets {}.

Practical Example 1: Insert Multiple Students

Let's insert three student records into the students collection.

db.students.insertMany([
    {
        name: "Amit",
        age: 22,
        course: "Python",
        city: "Raipur",
        status: "Active"
    },
    {
        name: "Priya",
        age: 20,
        course: "Java",
        city: "Durg",
        status: "Active"
    },
    {
        name: "Rohit",
        age: 23,
        course: "PHP",
        city: "Bilaspur",
        status: "Inactive"
    }
])

Expected Output:

{
    acknowledged: true,
    insertedIds: {
        '0': ObjectId("..."),
        '1': ObjectId("..."),
        '2': ObjectId("...")
    }
}

Explanation:

  • acknowledged: true indicates that MongoDB acknowledged the operation.

  • insertedIds contains the IDs assigned to the inserted documents.

  • The indexes 0, 1, and 2 correspond to the documents in the input array.

Practical Example 2: Insert Multiple Employees

db.employees.insertMany([
    {
        name: "Suresh",
        age: 30,
        department: "HR",
        salary: 30000
    },
    {
        name: "Neha",
        age: 26,
        department: "IT",
        salary: 40000
    },
    {
        name: "Vikas",
        age: 29,
        department: "Sales",
        salary: 32000
    }
])

This command inserts three employee records into the employees collection.

Practical Example 3: Insert Multiple Products

db.products.insertMany([
    {
        productName: "Keyboard",
        price: 1200,
        stock: 25,
        category: "Accessories"
    },
    {
        productName: "Mouse",
        price: 700,
        stock: 40,
        category: "Accessories"
    },
    {
        productName: "Monitor",
        price: 12000,
        stock: 15,
        category: "Electronics"
    }
])

This example inserts multiple product records into the products collection.

✦ 5. How to View Inserted Documents

After inserting documents, you can use the find() method to retrieve and verify the records.

Example: Display all students

db.students.find()

This command displays all documents stored in the students collection.

Example: Display all employees

db.employees.find()

Example: Display all products

db.products.find()

You can also search for a particular document using a condition.

db.students.find({
    city: "Raipur"
})

This query displays student documents whose city is Raipur.

✦ 6. Difference Between insertOne() and insertMany()

Both methods insert documents into MongoDB, but they are used for different situations.

Feature insertOne() insertMany()
Purpose Inserts one document Inserts multiple documents
Input Single document object Array of documents
Brackets {} [] containing {}
Use case Adding one record Adding multiple records
Result Returns insertedId Returns insertedIds

Example of insertOne():

db.students.insertOne({
    name: "Karan",
    age: 22,
    course: "JavaScript"
})

Example of insertMany():

db.students.insertMany([
    {
        name: "Riya",
        age: 21,
        course: "Python"
    },
    {
        name: "Mohit",
        age: 23,
        course: "PHP"
    }
])

When should you use insertOne()?

Use insertOne() when you need to insert only one document.

When should you use insertMany()?

Use insertMany() when you need to insert multiple documents in one operation.

✦ 7. Understanding Ordered and Unordered Inserts

MongoDB's insertMany() method supports ordered and unordered insertion.

A. Ordered Insert

By default, insertMany() uses ordered insertion.

db.students.insertMany(
    [
        { name: "Student A", age: 20 },
        { name: "Student B", age: 21 },
        { name: "Student C", age: 22 }
    ],
    { ordered: true }
)

With ordered: true, MongoDB processes documents in their specified order. If an insertion error occurs, MongoDB stops processing the remaining documents in that batch.

B. Unordered Insert

You can use ordered: false to allow MongoDB to continue processing other documents if one document fails.

db.students.insertMany(
    [
        { name: "Student D", age: 23 },
        { name: "Student E", age: 24 },
        { name: "Student F", age: 25 }
    ],
    { ordered: false }
)

With unordered insertion, MongoDB attempts to insert the remaining documents even if an individual document causes an error.

Important: The final result may include write errors. Always check the result and verify which documents were inserted.

✦ 8. Insert Documents with Custom _id

MongoDB automatically generates an _id for each document if you do not provide one.

However, you can also specify your own _id.

Example:

db.students.insertOne({
    _id: 101,
    name: "Ankit",
    age: 21,
    course: "MongoDB"
})

Here, the document uses 101 as its _id.

You can also use custom IDs with insertMany().

db.students.insertMany([
    {
        _id: 102,
        name: "Sneha",
        age: 22,
        course: "Python"
    },
    {
        _id: 103,
        name: "Vikas",
        age: 23,
        course: "Java"
    }
])

Important: Every _id value in a collection must be unique. If you try to insert a document with an _id that already exists, MongoDB reports a duplicate key error.

✦ 9. Common Errors While Using insertOne() and insertMany()

Beginners may face some common errors while inserting documents.

1. Duplicate _id Error

Every document in a collection must have a unique _id.

If you insert a document with an existing _id, MongoDB returns a duplicate key error.

Solution: Use a new unique _id or allow MongoDB to generate one automatically.

2. Incorrect JSON-Like Syntax

Incorrect syntax can cause an error.

Incorrect example:

db.students.insertOne({
    name: "Rahul"
    age: 21
})

Correct example:

db.students.insertOne({
    name: "Rahul",
    age: 21
})

Notice the comma after the name field.

3. Missing Square Brackets in insertMany()

The insertMany() method expects an array of documents.

Correct example:

db.students.insertMany([
    { name: "Amit", age: 22 },
    { name: "Priya", age: 20 }
])

4. MongoDB Server Is Not Running

If MongoDB Server is not running, you may not be able to connect through mongosh.

Solution: Start the MongoDB service and verify your connection before running insertion commands.

5. Wrong Collection Name

Make sure you are using the correct collection name.

For example:

db.students.insertOne({
    name: "Rahul"
})

This command inserts into students, not student.

✦ 10. Complete Practical Example: Create a Student Database

Now let's perform a complete practical exercise using insertOne() and insertMany().

Step 1: Select the Database

use college

Step 2: Insert One Student

db.students.insertOne({
    name: "Rahul",
    age: 21,
    course: "MongoDB",
    city: "Raipur",
    status: "Active"
})

Step 3: Insert Multiple Students

db.students.insertMany([
    {
        name: "Amit",
        age: 22,
        course: "Python",
        city: "Durg",
        status: "Active"
    },
    {
        name: "Priya",
        age: 20,
        course: "Java",
        city: "Raipur",
        status: "Active"
    },
    {
        name: "Rohit",
        age: 23,
        course: "PHP",
        city: "Bilaspur",
        status: "Inactive"
    }
])

Step 4: Display All Student Records

db.students.find()

Step 5: Find Students from Raipur

db.students.find({
    city: "Raipur"
})

Step 6: Count Student Records

db.students.countDocuments()

This command returns the total number of documents in the students collection.

You have now successfully inserted one document, inserted multiple documents, and verified the stored records.

✦ 11. Practice Task for Students

Now it is your turn to practise.

Create a database named company and work with a collection named employees.

Complete the following tasks:

  1. Insert one employee using insertOne().

  2. Add employee name, age, department, salary, and city.

  3. Insert at least five employees using insertMany().

  4. Display all employee records using find().

  5. Insert one product into a separate products collection.

  6. Insert three more products using insertMany().

  7. Try inserting a document with a custom _id.

  8. Check the total number of employees using countDocuments().

Try these commands yourself to improve your MongoDB skills.

✦ Conclusion

The insertOne() and insertMany() methods are essential for adding data to MongoDB collections.

In this tutorial, you learned:

  • What document insertion means in MongoDB.

  • How to insert a single document using insertOne().

  • How to insert multiple documents using insertMany().

  • How to view inserted documents using find().

  • The difference between ordered and unordered insertion.

  • How to use custom _id values.

  • Common insertion errors and their solutions.

These methods are frequently used when building database-driven applications. Practise these commands regularly to develop a strong understanding of MongoDB.

At Param Classes, we focus on practical programming concepts that help students build real-world development skills.

Official Learning Resources:

Learn Today, Grow Tomorrow — Param Classes.

←
Post 11 of 35
→