On this page
Overview
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 the bulkWrite() Example: Full File
section of the Bulk Operations guide.
A Note About _id
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.
Insert a Single Document
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.
Example
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:
API Documentation on insertOne()
API Documentation on InsertOneResult
Server manual entry on insertOne()
insertOne() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Connect to MongoDB guide. This example
also uses the movies
collection in the sample_mflix
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas by
following the Get Started with Atlas Guide.
The following code is a complete, standalone file that performs an insert one operation:
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 // Create a new client and connect to MongoDB 7 const client = new MongoClient(uri); 8 9 async function run() { 10 try { 11 // Connect to the "sample_mflix" database and access its "movies" collection 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create a document to insert 16 const doc = { 17 title: "Charade", 18 genres: ["Comedy", "Romance", "Thriller"], 19 year: 1963, 20 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], 21 } 22 // Insert the defined document into the "movies" collection 23 const result = await movies.insertOne(doc); 24 25 // Print the ID of the inserted document 26 console.log(`A document was inserted with the _id: ${result.insertedId}`); 27 } finally { 28 // Close the MongoDB client connection 29 await client.close(); 30 } 31 } 32 // Run the function and handle any errors 33 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 title: string; 10 content: string[]; 11 year: number; 12 cast: string[]; 13 } 14 15 async function run() { 16 try { 17 const database = client.db("sample_mflix"); 18 // Specifying a Schema is optional, but it enables type hints on 19 // finds and inserts 20 const movies = database.collection<Movie>("movies"); 21 const result = await movies.insertOne({ 22 title: "Charade", 23 genres: ["Comedy", "Romance", "Thriller"], 24 year: 1963, 25 cast: ["Cary Grant", "Audrey Hepburn", "Walter Matthau"], 26 }); 27 console.log(`A document was inserted with the _id: ${result.insertedId}`); 28 } finally { 29 await client.close(); 30 } 31 } 32 run().catch(console.dir);
Running the preceding example results in the following output:
A document was inserted with the _id: ...
Insert Multiple Documents
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.
Example
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:
API Documentation on insertMany()
API Documentation on InsertManyResult
API Documentation on PkFactory
Server manual entry on insertMany()
insertMany() Example: Full File
Note
Example Setup
This example connects to an instance of MongoDB by using a
connection URI. To learn more about connecting to your MongoDB
instance, see the Connect to MongoDB guide. This example
also uses the movies
collection in the sample_mflix
database
included in the Atlas sample datasets. You
can load them into your database on the free tier of MongoDB Atlas by
following the Get Started with Atlas Guide.
The following code is a complete, standalone file that performs an insert many operation:
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 async function run() { 9 try { 10 11 // Get the database and collection on which to run the operation 12 const database = client.db("sample_mflix"); 13 const movies = database.collection("movies"); 14 15 // Create an array of documents to insert 16 const moviesToInsert = [ 17 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, 18 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, 19 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, 20 ]; 21 22 // Prevent additional documents from being inserted if one fails 23 const options = { ordered: true }; 24 25 // Execute insert operation 26 const result = await movies.insertMany(moviesToInsert, options); 27 28 // Print result 29 console.log(`${result.insertedCount} documents were inserted`); 30 } finally { 31 await client.close(); 32 } 33 } 34 run().catch(console.dir);
1 import { MongoClient } from "mongodb"; 2 3 // Replace the uri string with your MongoDB deployment's connection string. 4 const uri = "<connection string uri>"; 5 6 const client = new MongoClient(uri); 7 8 interface Movie { 9 title: string; 10 genres: string[]; 11 year: number; 12 cast: string[]; 13 } 14 15 async function run() { 16 try { 17 const database = client.db("sample_mflix"); 18 // Specifying a schema is optional, but it enables type hints on 19 // finds and inserts 20 const movies = database.collection<Movie>("movies"); 21 22 const result = await movies.insertMany( 23 { title: "Arsenic and Old Lace", genres: ["Comedy", "Romance"], year: 1944, cast: ["Cary Grant", "Priscilla Lane", "Raymond Massey"] }, 24 { title: "Ball of Fire", genres: ["Comedy", "Romance"], year: 1941, cast: ["Gary Cooper", "Barbara Stanwyck", "Oskar Homolka"] }, 25 { title: "I Married a Witch", genres: ["Comedy", "Fantasy", "Romance"], year: 1942, cast: ["Veronica Lake", "Fredric March", "Susan Hayward"] }, 26 { ordered: true } 27 ); 28 console.log(`${result.insertedCount} documents were inserted`); 29 } finally { 30 await client.close(); 31 } 32 } 33 run().catch(console.dir);
Running the preceding example results in the following output:
3 documents were inserted
API Documentation
To learn more about any of the types or methods discussed in this guide, see the following API documentation: