Adding Documents to MongoDB: The insertOne() Method
Learn how to efficiently add single documents to MongoDB collections using the insertOne() method. This guide will provide you with the necessary knowledge and examples to effectively populate your MongoDB databases with individual documents.
MongoDB - Insert Single Document in a Collection using insertOne()
In MongoDB, you can use various methods to insert documents into a collection:
insertOne()
- Inserts a single document.insert()
- Inserts one or more documents.insertMany()
- Inserts multiple documents.
Using insertOne()
The insertOne()
method is used to insert a single document into a collection. The syntax is:
Syntax
db.collection.insertOne(document, [writeConcern])
Parameters:
document
: The document to insert.writeConcern
: Optional. Document expressing the write concern.
Example: Insert a Single Document
Example: Insert Document
db.employees.insertOne({
firstName: "John",
lastName: "King",
email: "john.king@abc.com"
})
Output:
Output
{
acknowledged: true,
insertedId: ObjectId("616d44bea861820797edd9b0")
}
The insertOne()
method returns an object with:
acknowledged
: Indicates if the operation was successful.insertedId
: The unique identifier for the inserted document.
View Inserted Document in mongosh
Insert and View Document
db.employees.find().pretty()
Output:
Output
{
_id: ObjectId("616d44bea861820797edd9b0"),
firstName: "John",
lastName: "King",
email: "john.king@abc.com"
}
Note: MongoDB does not enforce schemas, so you can insert documents with different fields into the same collection.
Inserting Documents with Custom _id
You can manually specify the _id
field value:
Example: Insert with Custom _id
db.employees.insertOne({
_id: "1",
firstName: "John",
lastName: "King",
email: "john.king@abc.com"
})
Output:
Output
{
acknowledged: true,
insertedId: "1"
}
Ensure that the _id
value is unique to avoid errors. Attempting to insert a document with a duplicate _id
will result in an error:
Example: Duplicate _id Error
db.employees.insertOne({
_id: "1",
firstName: "John",
lastName: "King",
email: "john.king@abc.com"
})
Output:
Output
MongoServerError: E11000 duplicate key error collection: humanResourceDB.employees index: _id_ dup key: { _id: "1" }
Use the insertOne()
method to insert documents into MongoDB collections, and manage custom _id
values carefully to ensure uniqueness.