MongoDB Insert Method

The MongoDB insert method is used to adding one or more documents (also known as records or data entries) to a MongoDB collection.

Insert a Single Document

We use insertOne() to add a single document to a collection.

db.myCollection.insertOne({ name: "Harry", age: 30 });
        

Insert Multiple Documents

We use insertMany() method to insert mulitple documents into a collection in an array.


  db.myCollection.insertMany([
  { name: "Alice", age: 25 },
  { name: "Bob", age: 28 }
]);

        

Insert with Specified _id

In MongoDB when we insert a document, you can specify the _id field when inserting a document to set a custom identifier.

db.myCollection.insertOne({ _id: "customID", name: "Custom", age: 35 });
        

Checking Inserted Documents

After insertion the documents into the collection, we can use find()method to verify the inserted documents.

db.myCollection.find();
        

Insert Result

Insert operations return an object with an acknowledged field indicating success and _id for the inserted document.

const result = db.myCollection.insertOne({ name: "Sarah", age: 27 });
printjson(result);        

Insert with Write Concern

You can specify write concern options like { w: "majority" } for safe writes.

db.myCollection.insertOne(
  { name: "Tom", age: 32 },
  { writeConcern: { w: "majority" } }
);          
          

Bypass Validation

To insert documents without validation, set bypassDocumentValidation to true.


db.myCollection.insertOne(
  { name: "Grace", age: 29 },
  { bypassDocumentValidation: true }
);
     

Insert Duplicates

Inserting a document with an existing _idwill replace the existing document.

db.myCollection.insertOne({ _id: "customID", name: "Updated", age: 35 });

Bulk Inserts

For efficient bulk inserts, use initializeUnorderedBulkOp or initializeOrderedBulkOp.

const bulk = db.myCollection.initializeUnorderedBulkOp();
bulk.insert({ name: "Lucas", age: 45 });
bulk.insert({ name: "Ella", age: 33 });
bulk.execute();