MongoDB insertOne() Method (original) (raw)

Last Updated : 5 May, 2026

insertOne() adds a single document to a collection.

**Syntax:

db.collection_name.insertOne(,{ writeConcern: })

Return Value of insertOne()

The insertOne() method returns the following:

Examples of MongoDB insertOne()

Here are few examples to understand how insertOne() works in MongoDB. In the following examples, we are working with:

1

Example 1: Insert a Document without Specifying an _id Field

We are inserting the document whose name is Akshay and marks is 500 in the student collection. MongoDB will automatically assign a unique _id field to this document.

**Query:

db.student.insertOne({Name: "Tim", Marks: 500})

**Output:

2

MongoDB has inserted the document with a new ObjectId automatically generated for the _id field.

Example 2: Insert a Document Specifying an _id Field

We are inserting a document whose unique id is Stu102, name is Vishal, and marks is 230 in the student collection

**Query:

db.student.insertOne({_id: "Stu102", Name: "Ron", Marks: 220})

**Output:

3

We specified the _id as "Stu102", and MongoDB inserts the document successfully.

Example 3: Handling Write Concern with insertOne()

A custom write concern can be specified to ensure data is written to multiple nodes before being considered committed.

**Query:

db.student.insertOne(
{ Name: "Maria", Marks: 420 },
{ writeConcern: { w: 1, j: true, wtimeout: 5000 } }
)

**Output:

Screenshot-2026-02-04-112618

Common Errors with insertOne()

While the insertOne() method is quite efficient, you might encounter some errors when: