MongoDB Insert() Method (original) (raw)

Last Updated : 28 Jan, 2025

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

**Syntax:

db.Collection_name.insert(
<document or [document1, document2,…]>,
{
writeConcern: ,
ordered:
})

**Parameters

Optional parameters

**Return Type

**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:

**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:

insert single document in mongodb collection example 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:

insert multiple documents in mongodb collection example 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:

Insert-a-Document-with-_id-field

**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.

db.collection.insert(document, { writeConcern: { w: 1, j: true } })

2. Create Collection

In MongoDB, collections are created implicitly when a document is inserted into a non-existent collection.

db.newCollection.insert({ name: "Alice", age: 25 })

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