Open In App

MongoDB – Insert() Method

The insert() method in MongoDB inserts documents in the MongoDB collection. This method is also used to create a new collection by inserting documents.

Important Points:

Note: This method is deprecated in Mongosh. Instead, use insertOne() and Insert()many methods to insert new documents in the MongoDB collection.



Syntax

db.Collection_name.insert(
<document or [document1, document2,...]>,
{
    writeConcern: <document>,
    ordered: <boolean>
})

Parameters:

Below are optional parameters:

Return Type:

MongoDB insert Method Examples

Let’s see some examples of MongoDB db.Collection.insert() Method to insert new documents in the MongoDB Collection.

In the following examples, we are working with:



Database: gfg

Collection: student

Document: No document but, we want to insert in the form of the student name and student marks.

Insert Single Document in MongoDB Collection Example

Here, we insert a document in the “student” collection whose name is “Akshay” and marks is “500” using insert() method.

db.student.insert({Name: "Akshay", Marks: 500})

Output:

Insert Multiple Documents in MongoDB Collection Example

Here, we insert multiple documents in the collection by passing an array of documents in the insert method.

db.student.insert([{Name: "Bablu", Marks: 550}, 
                                {Name: "Chintu", Marks: 430},
                                {Name: "Devanshu", Marks: 499}
])

Output:

Insert a Document with _id field Example

Here, we insert a document in the student collection with _id field.

db.student.insert({_id: 102,Name: "Anup", Marks: 400})

Output:

Article Tags :