MongoDB Insert() Method (original) (raw)

Last Updated : 10 Feb, 2026

The insert() method in MongoDB is used to add one or more documents to a collection, automatically generating a unique _id when not provided, though it is now deprecated in favor of newer methods.

**Syntax

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

**Parameters

**Optional parameters

**Return Type

Examples of MongoDB Insert() Method

Example 1: Insert a Document without Specifying an _id Field

Insert a document into the "student" collection with the name "Lee" and marks "500". By not specifying the _id field, MongoDB will automatically generate a unique identifier for this document.

**Query:

db.student.insert({Name: "Lee", Marks: 500})

**Output:

Screenshot-2026-02-04-104818

Example 2:Insert Multiple Documents

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: "Ben", Marks: 550},
{Name: "Nicol", Marks: 430},
{Name: "Denis", Marks: 499}
])

**Output:

Screenshot-2026-02-04-105335

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

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: "Ryan", Marks: 400})

**Output:

Screenshot-2026-02-04-105608

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 defines how MongoDB acknowledges write operations, using options like w (write) and j (journal) to control data durability.

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: "Alex", age: 25 })

db.createCollection("explicitCollection")
db.explicitCollection.insert({ name: "Luca", age: 30 })

3. _id Field

The _id field is MongoDB’s primary key, must be unique, is auto-generated if omitted, and custom duplicate values cause errors.