Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Insert a Document

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. To perform any of those operations, that information, such as user profiles and orders, needs to exist in MongoDB. For that information to exist, you need to first perform an insert operation.

An insert operation inserts a single or multiple documents in MongoDB using the insertOne(), insertMany() and bulkWrite() methods.

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 additional 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 creates and inserts a document using the insertOne() method:

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

Your output should look something like this:

A document was inserted with the _id: 60c79c0f4cc72b6bb31e3836

For additional 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 at the third document and the documents prior to the error get inserted into your collection.

Note

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

try {
const docs = [
{ "_id": 1, "color": "red"},
{ "_id": 2, "color": "purple"},
{ "_id": 1, "color": "yellow"},
{ "_id": 3, "color": "blue"}
];
const insertManyresult = await collection.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 should look something like this:

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 creates and adds three documents using the insertMany() method:

const docs = [
{ name: "Sicilian pizza", shape: "square" },
{ name: "New York pizza", shape: "round" },
{ name: "Grandma pizza", shape: "square" }
];
const insertManyresult = await collection.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 should look something like this:

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

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

←  Write OperationsGenerate Custom Values for _id →