Last Updated : 10 Jun, 2025
In MongoDB, insert operations are used to insert new documents in the collection. Whether you are creating a new collection or inserting into an existing one, MongoDB makes it easy to insert single documents by employing the insertOne() method within the Mongo shell. In case the collection does not exist, the insertOne() operation will create the collection by inserting the document. When the collection already exists, the operation will just insert new documents into the existing collection
What isinsertOne()
Method?
The insertOne() function in MongoDB is employed to add a single document into a collection. This function can be used within multi-document transactions as well, which guarantees atomicity and consistency in case of requirement. In this function, you can insert a document in the collection with or without _id field. If you insert a document without _id field, then MongoDB itself inserts a _id field and populates it with a unique ObjectId.
How DoesinsertOne()
Work?
_id
field._id
field, MongoDB automatically generates a unique ObjectId for the document._id
if needed.Syntax:
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
Parameters:
Return
The method returns an object containing:
_id
of the inserted document.student
Collection of GeeksforGeeks
Database
In the following examples, we are working with:
Database: GeeksforGeeks1. Inserting a Single Document without _id field:
Collection: student
In this example, we are inserting a document in the student collection without _id field using db.collection.insertOne() method.
This inserts a new document into the student
collection with an automatically generated _id
.
In this example, we are inserting a document in the student collection with _id field using db.collection.insertOne() method.
Here, the document uses 101
as the _id
instead of MongoDB generating one.
insertOne()
_id
values to avoid duplicate key errors.insertMany()
for better performance.The insertOne()
method is a straightforward and powerful way to add single documents into your MongoDB collections. Understanding its syntax, parameters, and return structure helps ensure your data insertion is accurate and efficient. Whether you’re inserting with an automatic or custom _id
, MongoDB provides flexibility and reliability in managing your data. It’s an essential tool for developers working with MongoDB who need to manage individual records efficiently.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4