Docs Menu

Docs HomeDevelop ApplicationsMongoDB DriversNode.js

Insert a Document

Note

If you specify a callback method, insertOne() returns nothing. If you do not specify one, this method returns a Promise that resolves to the result object when it completes. See our guide on Promises and Callbacks for more information, or the API documentation for information on the result object.

You can insert a document into a collection using the collection.insertOne() method. To insert a document, define an object that contains the fields and values that you want to store. If the specified collection does not exist, the insertOne() method creates the collection.

You can specify additional query options using the options parameter. For more information on the method parameters, see the insertOne() API documentation. You can also pass a callback method as an optional third parameter. For more information on this method, see the insertOne() API documentation.

The insertedId field of this object is the _id of the inserted document. If the operation fails to create a document, the insertedCount field of this object has a value of 0. If the operation creates a document, the insertedCount field of this object has a value of 1.

Note

This example connects to an instance of MongoDB and uses a sample data database. To learn more about connecting to your MongoDB instance and loading this database, see the Usage Examples guide.

1const { MongoClient } = require("mongodb");
2
3// Replace the uri string with your MongoDB deployment's connection string.
4const uri =
5 "mongodb+srv://<user>:<password>@<cluster-url>?writeConcern=majority";
6
7const client = new MongoClient(uri, {
8 useNewUrlParser: true,
9 useUnifiedTopology: true,
10});
11
12async function run() {
13 try {
14 await client.connect();
15
16 const database = client.db("sample_mflix");
17 const movies = database.collection("movies");
18 // create a document to be inserted
19 const doc = { name: "Red", town: "kanto" };
20 const result = await movies.insertOne(doc);
21
22 console.log(
23 `${result.insertedCount} documents were inserted with the _id: ${result.insertedId}`,
24 );
25 } finally {
26 await client.close();
27 }
28}
29run().catch(console.dir);
←  Insert OperationsInsert Multiple Documents →