MongoDB – Insert Single Document in a Collection using insertOne()
MongoDB provides the following methods to insert documents into a collection:
- insertOne() – Inserts a single document
- insert () (Deprecated) – Inserts one or more documents
- insertMany() – Insert multiple documents
insertOne()
Syntax:
db.collection.insertOne(document)
The following inserts a document into employees
collection.
Example: insertOne()
db.employees.insertOne({ firstName: "John", lastName: "King", email: "john.king@abc.com" })
Output
{ acknowledged: true, insertedId: ObjectId("616d44bea861820797edd9b0") }
Explanation: We passed a document to the insertOne()
method. Notice that we haven’t specified _id
field. So, MongoDB inserts a document to a collection with the auto-generated unique _id
field. It returns an object with a boolean field acknowledged
that indicates whether the insert operation is successful or not, and insertedId
field with the newly inserted _id
value.
Insert _id Manually
It is not necessary to insert auto-generated _id
value. You can manually specify a unique value for the _id
field, as shown below.
Example: Insert a Document
db.employees.insertOne({ _id:"1", firstName: "John", lastName: "King", email: "john.king@abc.com" })
Output
{ acknowledged: true, insertedId: 1 }
Note that while adding your custom value to _id
field, a value must be unique; otherwise, it will throw an error. The following tries to add the same _id
value.
Example: Insert a Document
db.employees.insertOne({ _id:"1", firstName: "John", lastName: "King", email: "john.king@abc.com" })
Output
MongoServerError: E11000 duplicate key error collection: humanResourceDB.employees index: _id_ dup key: { _id: "1" }
Note: MongoDB is NoSQL database. So, it does not enforce schema to any collection. It means you can insert a document with any fields to a collection. For example, the following inserts a document with different fields to the employees
collection.
Example: Insert a Document with different column label
db.employees.insertOne({ fName: "John", lName: "King", emailid: "john.king@abc.com" })
Some genuinely nice and utilitarian information on this internet site, besides I believe the style and design contains superb features.