MongoDB - Insert() Method
The insert()
method in MongoDB is a fundamental operation used to add new documents to a collection. It allows inserting one or multiple documents in a single execution with MongoDB automatically generating a unique _id
field if not explicitly provided.
In this article, We will learn about the MongoDB Insert() method by understanding its behavior
along with multiple examples to illustrate its usage.
MongoDB Insert()
The insert()
method is a fundamental operation in MongoDB that is used to add new documents to a collection. This method is flexible, allowing developers to insert either a single document or multiple documents in a single operation, which can significantly enhance performance and reduce the number of database calls.
When a document is inserted, MongoDB automatically generates a unique _id
field if it is not provided by the user. This automatic generation of the _id
field ensures that each document can be uniquely identified, which is important for maintaining data integrity and facilitating efficient data retrieval.
Key Points
- _id Field: You can insert documents with or without the
_id
field. If a document is inserted without the_id
field, MongoDB will automatically add it and assign a uniqueObjectId
. If you provide an_id
field, its value must be unique to avoid a duplicate key error. - Multi-document Transactions: The
insert()
method can also be used within multi-document transactions. - Deprecation Notice: The
insert()
method is deprecated in the MongoDB shell (mongosh). Instead, useinsertOne()
andinsertMany()
methods to insert new documents into a MongoDB collection.
Syntax:
db.Collection_name.insert(
<document or [document1, document2,...]>,
{
writeConcern: <document>,
ordered: <boolean>
})
Parameters
- document: A document or array of documents to insert into the collection. Documents are a structure created of file and value pairs, similar to JSON objects.
- optional: The second parameter is optional which includes writeConcern and ordered.
Optional parameters
- writeConcern: It is only used when you do not want to use the default write concern. The type of this parameter is a document.
- ordered: The default value of this parameter is true. If it is true, it inserts documents in the ordered manner. Otherwise, it randomly inserts documents.
Return Type
- This method returns WriteResult when you insert single document in the collection.
- This method returns BulkWriteResult when you insert multiple documents in the collection.
Examples of MongoDB Insert() Method
In this section, we will explore practical examples of the db.Collection.insert()
method to demonstrate how to insert new documents into a MongoDB collection. For our examples, we will be working with the following setup:
- Database: gfg
- Collection: student
- Document: No document but, we want to insert in the form of the student name and student marks.
Example 1: Insert a Document without Specifying an _id
Field
In this example, we insert a document into the "student" collection with the name "Akshay" and marks "500". By not specifying the _id
field, MongoDB will automatically generate a unique identifier for this document.
Query:
db.student.insert({Name: "Akshay", Marks: 500})
Output:

Explanation:
This operation creates a new document in the student
collection. The document will look like this: { "_id": ObjectId("generated_id"), "Name": "Akshay", "Marks": 500 }
. The _id
field is automatically generated by MongoDB.
Example 2: Insert Multiple Documents
In this example, we insert multiple documents into the collection by passing an array of documents to the insert
method. This allows for batch insertion, which is more efficient than inserting documents one at a time.
Query:
db.student.insert([
{Name: "Bablu", Marks: 550},
{Name: "Chintu", Marks: 430},
{Name: "Devanshu", Marks: 499}
])
Output:

Explanation:
This operation inserts three new documents into the student
collection. Each document will have its own automatically generated _id
.
Example 3: Insert a Document Specifying an _id
Field
In this example, we insert a document into the student
collection with a specified _id
field. This demonstrates how to manually set the identifier for a document.
Query:
db.student.insert({_id: 102, Name: "Anup", Marks: 400})
Output:

Explanation:
This operation creates a new document with a custom _id
of 102
. The document will look like this: { "_id": 102, "Name": "Anup", "Marks": 400 }
. If another document with _id: 102
already exists, this operation will result in a duplicate key error.
Behaviors of Insert() Method
The insert
method in MongoDB is used to add documents to a collection. Here’s how it behaves based on the aspects of Write Concern, Create Collection and the _id
field:
1. Write Concern
Write Concern determines the level of acknowledgment requested from MongoDB for write operations to ensure that the data is written to the desired number of nodes. It can be configured using the w
(write) and j
(journal) options.
- Default Write Concern: If not specified, MongoDB uses the default write concern, which is to acknowledge the write operation after it has been written to the primary node.
- Configurable Write Concern: You can specify the write concern as an option to the
insert
method. For example:
db.collection.insert(document, { writeConcern: { w: 1, j: true } })
w
: 1
means the operation will be acknowledged only after the primary node confirms the write.j
: true
means the write operation will be acknowledged only after the write has been committed to the journal.
2. Create Collection
In MongoDB, collections are created implicitly when a document is inserted into a non-existent collection.
- Implicit Collection Creation: If the specified collection does not exist, MongoDB will create it implicitly when the first document is inserted.
db.newCollection.insert({ name: "Alice", age: 25 })
- Explicit Collection Creation: While not common, we can also create a collection explicitly using the
createCollection
method before inserting documents.
db.createCollection("explicitCollection")
db.explicitCollection.insert({ name: "Bob", age: 30 })
3. _id
Field
The _id
field in MongoDB is the primary key for documents in a collection. It must be unique for each document. If not provided, MongoDB automatically generates an ObjectId
. Custom values can be specified, but duplicates will result in errors.
Conclusion
In MongoDB, the insert()
method plays a crucial role in efficiently adding documents to collections, ensuring that each document has a unique identifier through the _id
field. This method is not only flexible but also powerful, allowing for the insertion of complex documents that can include nested fields and arrays. While the insert()
method has been deprecated in modern MongoDB shells, understanding its functionality is essential for grasping the foundational concepts of document insertion in MongoDB