Navigation

Insert a Document

In this section, we show you how to call the write operations to insert documents from a collection in your MongoDB database.

If you want to add new documents to a collection, you can use the insertOne() or the insertMany() method. These methods accept single or multiple documents, respectively. The driver automatically generates a unique _id field for documents unless specified.

You can specify the document to be inserted by the insertOne() write operation in a JSON object as follows:

const pizzaDocument = {
name: "Neapolitan pizza",
shape: "round",
toppings: [ "San Marzano tomatoes", "mozzarella di bufala cheese" ],
};

To insert the document into the collection reference pizzaCollection, specify the document as the first parameter of your call to the insertOne() method as shown below:

const result = await pizzaCollection.insertOne(pizzaDocument);

You can print the number of documents inserted by accessing the insertedCount field of the operation result as follows:

console.dir(result.insertedCount); // should print 1 on successful insert

For a runnable example, see the insertOne() usage example.

You can specify the documents to be inserted by the insertMany() write operation in an array of JSON objects as follows:

const pizzaDocuments = [
{ name: "Sicilian pizza", shape: "square" },
{ name: "New York pizza", shape: "round" },
{ name: "Grandma pizza", shape: "square" },
];

To insert the array of documents into the collection reference pizzaCollection, specify the array as the first parameter of your call to the insertMany() method as shown below:

const result = await pizzaCollection.insertMany(pizzaDocuments);

You can print the number of documents inserted by accessing the insertedCount field of the operation result as follows:

console.dir(result.insertedCount); // should print 3 on successful insert

For a runnable example, see the insertMany() usage example.

Give Feedback