![]() |
VOOZH | about |
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
insertOne() 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.
insertOne() 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 DatabaseIn the following examples, we are working with:
Database: GeeksforGeeks
Collection: student
In this example, we are inserting a document in the student collection without _id field using db.collection.insertOne() method. π Image
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. π Image
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.