Mass insertion in MongoDB

For mass insertion in MongoDB, use the insertMany() method to insert multiple documents into a collection in a single operation. This is more efficient than inserting documents individually using multiple insert() calls.

Syntax

db.collection.insertMany([
    { document1 },
    { document2 },
    { document3 }
]);

Example

Let us create a collection with multiple bank customer documents ?

db.demo729.insertMany([
    { BankName: "HDFC Bank", cardType: "Credit", "CustomerName": [{Name: "Chris", Age: 25}] },
    { BankName: "ICICI Bank", cardType: "Debit", "CustomerName": [{Name: "Bob", Age: 22}] },
    { BankName: "Kotak Bank", cardType: "Debit", "CustomerName": [{Name: "David", Age: 23}] }
]);
{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("5eac510d56e85a39df5f6333"),
        ObjectId("5eac510d56e85a39df5f6334"),
        ObjectId("5eac510d56e85a39df5f6335")
    ]
}

Verify Result

Display all documents from the collection using the find() method ?

db.demo729.find().pretty();
{
    "_id" : ObjectId("5eac510d56e85a39df5f6333"),
    "BankName" : "HDFC Bank",
    "cardType" : "Credit",
    "CustomerName" : [
        {
            "Name" : "Chris",
            "Age" : 25
        }
    ]
}
{
    "_id" : ObjectId("5eac510d56e85a39df5f6334"),
    "BankName" : "ICICI Bank",
    "cardType" : "Debit",
    "CustomerName" : [
        {
            "Name" : "Bob",
            "Age" : 22
        }
    ]
}
{
    "_id" : ObjectId("5eac510d56e85a39df5f6335"),
    "BankName" : "Kotak Bank",
    "cardType" : "Debit",
    "CustomerName" : [
        {
            "Name" : "David",
            "Age" : 23
        }
    ]
}

Conclusion

The insertMany() method efficiently inserts multiple documents in a single database operation. It returns an acknowledgment with the generated ObjectIds for all inserted documents, making it ideal for bulk data insertion scenarios.

Updated on: 2026-03-15T03:52:12+05:30

167 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements