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:
- You can insert documents with or without the _id field. If you insert a document in the collection without the _id field, then MongoDB will automatically add an _id field and assign it with a unique ObjectId. And if you insert a document with the _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.
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:
- 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.
Below are 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.
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:
Contact Us