Open In App
Related Articles

MongoDB Insert() Method – db.Collection.insert()

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In MongoDB, the insert() method inserts a document or documents into the collection. It takes two parameters, the first parameter is the document or array of the document that we want to insert and the remaining are optional.

  • Using this method you can also create a collection by inserting documents.
  • You can insert documents with or without _id field. If you insert a document in the collection without _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with _id field, then the value of the _id field must be unique to avoid the duplicate key error.
  • This method can also be used inside multi-document transactions.

Syntax:

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

Parameters:

  • document : A document or array of documents to insert into the collection.. Documents are a structure created of file and value pairs, similar to JSON objects.
  • optional : The second parameter is optional which includes writeConcern and ordered.

Optional Parameters:

  • writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
  • ordered: The default value of this parameter is true. If it is true, it inserts documents in the ordered manner. Otherwise, it randomly inserts documents.

Return Type:

  • This method returns WriteResult when you insert single document in the collection.
  • This method returns BulkWriteResult when you insert multiple documents in the collection.

Examples:

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 the document whose name is Akshay and marks is 500

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 the collection

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

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

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

Output:


Last Updated : 05 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads