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:
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.
Contact Us