MongoDB insertOne() Method – db.Collection.insertOne()
In MongoDB, insertOne() method inserts a document into the collection. This method inserts only one document at a time.
- 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 throw either writeError or writeConcernError exception.
- This method can also be used inside multi-document transactions.
Syntax:
db.Collection_name.insertOne(
<document>,
{
writeConcern: <document>
})
Parameters:
- The first parameter is the document. Documents are a structure created of file and value pairs, similar to JSON objects.
- The second parameter is optional.
Optional Parameter:
writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
Return:
This method returns :
- Boolean acknowledged as true if write concern was enabled or false if write concern was disabled.
- The insertedId field with the _id value of the inserted document.
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 a single document without specifying the _id field
Here, we are inserting the document whose name is Akshay and marks is 500 in the student collection.
db.student.insertOne({Name: "Akshay", Marks: 500})
- Insert a single document with _id field
Here, we are inserting a document whose unique id is Stu102, name is Vishal, and marks is 230 in the student collection
db.student.insertOne({_id: "Stu102", Name: "Vishal", Marks: 230})
Contact Us