Docs Menu
Docs Home
/ / /
Node.js Driver
/ / /

Insert Documents

On this page

  • Overview
  • A Note About _id
  • Insert a Single Document
  • Insert Multiple Documents

In this guide, you can learn how to insert documents into MongoDB.

You can use MongoDB to retrieve, update, and delete information that is already stored in MongoDB. To store information, use an insert operation.

An insert operation inserts one or more documents into a MongoDB collection. The Node.js driver provides the following methods to perform insert operations:

  • insertOne()

  • insertMany()

  • bulkWrite()

Tip

Interactive Lab

This page includes a short interactive lab that demonstrates how to insert data by using the insertOne() method. You can complete this lab directly in your browser window without installing MongoDB or a code editor.

To start the lab, click the Open Interactive Tutorial button at the top of the page. To expand the lab to a full-screen format, click the full-screen button (⛶) in the top-right corner of the lab pane.

The following sections focus on insertOne() and insertMany(). For an example on how to use the bulkWrite() method, see our runnable Bulk Operations Example.

When inserting a document, MongoDB enforces one constraint on your documents by default. Each document must contain a unique _id field.

There are two ways to manage this field:

  • You can manage this field yourself, ensuring each value you use is unique.

  • You can let the driver automatically generate unique ObjectId values with the primary key factory.

Unless you have provided strong guarantees for uniqueness, we recommend you let the driver automatically generate _id values.

Note

Duplicate _id values violate unique index constraints, resulting in a WriteError.

For more information about _id, see the Server manual entry on Unique Indexes.

Use the insertOne() method when you want to insert a single document.

On successful insertion, the method returns an InsertOneResult instance representing the _id of the new document.

The following example uses the insertOne() method to insert a new document into the myDB.pizzaMenu collection:

const myDB = client.db("myDB");
const myColl = myDB.collection("pizzaMenu");
const doc = { name: "Neapolitan pizza", shape: "round" };
const result = await myColl.insertOne(doc);
console.log(
`A document was inserted with the _id: ${result.insertedId}`,
);

Your output looks similar to the following text:

A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836

For more information on the classes and methods mentioned in this section, see the following resources:

Use the insertMany() method when you want to insert multiple documents. This method inserts documents in the order specified until an exception occurs, if any.

For example, assume you want to insert the following documents:

{ "_id": 1, "color": "red" }
{ "_id": 2, "color": "purple" }
{ "_id": 1, "color": "yellow" }
{ "_id": 3, "color": "blue" }

If you attempt to insert these documents, a WriteError occurs when the third document is processed, but the documents before the error are inserted into your collection.

Note

Use a try-catch block to get an acknowledgment for successfully processed documents before the error occurs:

const myDB = client.db("myDB");
const myColl = myDB.collection("colors");
try {
const docs = [
{ "_id": 1, "color": "red"},
{ "_id": 2, "color": "purple"},
{ "_id": 1, "color": "yellow"},
{ "_id": 3, "color": "blue"}
];
const insertManyresult = await myColl.insertMany(docs);
let ids = insertManyresult.insertedIds;
console.log(`${insertManyresult.insertedCount} documents were inserted.`);
for (let id of Object.values(ids)) {
console.log(`Inserted a document with id ${id}`);
}
} catch(e) {
console.log(`A MongoBulkWriteException occurred, but there are successfully processed documents.`);
let ids = e.result.result.insertedIds;
for (let id of Object.values(ids)) {
console.log(`Processed a document with id ${id._id}`);
}
console.log(`Number of documents inserted: ${e.result.result.nInserted}`);
}

The output consists of documents MongoDB can process and looks similar to the following:

A MongoBulkWriteException occurred, but there are successfully processed documents.
Processed a document with id 1
Processed a document with id 2
Processed a document with id 1
Processed a document with id 3
Number of documents inserted: 2

If you look inside your collection, you see the following documents:

{ "_id": 1, "color": "red" }
{ "_id": 2, "color": "purple" }

On successful insertion, the method returns an InsertManyResult instance representing the number of documents inserted and the _id of the new document.

The following example uses the insertMany() method to insert three new documents into the myDB.pizzaMenu collection:

const myDB = client.db("myDB");
const myColl = myDB.collection("pizzaMenu");
const docs = [
{ name: "Sicilian pizza", shape: "square" },
{ name: "New York pizza", shape: "round" },
{ name: "Grandma pizza", shape: "square" }
];
const insertManyresult = await myColl.insertMany(docs);
let ids = insertManyresult.insertedIds;
console.log(`${insertManyresult.insertedCount} documents were inserted.`);
for (let id of Object.values(ids)) {
console.log(`Inserted a document with id ${id}`);
}

Your output looks similar to the following:

3 documents were inserted.
Inserted a document with id 60ca09f4a40cf1d1afcd93a2
Inserted a document with id 60ca09f4a40cf1d1afcd93a3
Inserted a document with id 60ca09f4a40cf1d1afcd93a4

For more information on the classes and methods mentioned in this section, see the following resources:

Back

Write