Node.js MongoDB Insert Documents with insertOne() and insertMany()
In a Node.js application, you can insert a single document into a MongoDB collection with insertOne() and insert multiple documents with insertMany(). Both methods are available through the official MongoDB Node.js driver.
This tutorial explains how to connect Node.js to MongoDB, insert one document, insert many documents, verify the inserted records, and handle common insert details such as _id, embedded documents, and result objects.
Before inserting MongoDB documents from Node.js
Use the mongodb npm package in your Node.js project. If you are creating a new example project, install the driver first.
npm install mongodb
The examples in this page use a local MongoDB server and the database name newdb. If you use MongoDB Atlas or another remote deployment, replace the connection string with your own MongoDB URI.
Steps to insert documents into MongoDB collection using Node.js
Following is a step by step guide with an example to insert documents to MongoDB Collection from Node.js Application.
Step 1: Start MongoDB Service.
Run the following command to start MongoDB Service.
sudo service mongod start
Step 2: Get the base URL to MongoDB Service.
A simple hack to know the base url of MongoDB Service is to Open a Terminal and run Mongo Shell.
arjun@nodejs:~$ mongo
MongoDB shell version v3.4.9
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.9
Server has startup warnings:
2017-10-29T18:15:36.110+0530 I STORAGE [initandlisten]
While the Mongo Shell starts up, it echoes back the base url of MongoDB.
mongodb://127.0.0.1:27017
Step 3: Prepare the complete URL.
Append the Database name you want to connect to (say newdb), to the base URL.
mongodb://127.0.0.1:27017/newdb
Step 4: Create a MongoClient.
var MongoClient = require('mongodb').MongoClient;
Step 5: Make connection from MongoClient to the MongoDB Server with the help of URL.
MongoClient.connect(url, <callback_function>);
Once the MongoClient is done trying to make a connection, the callback function receives error and db object as arguments.
If the connection is successful, the db object points to the database, newdb.
Step 6: Insert documents to specified MongoDB Collection.
Following is the syntax of insertOne() and insertMany() methods used to insert documents to collection in MongoDB from Node.js.
insertOne()
db.collection(<collection_name>).insertOne(<document>, <callback_function>)
insertMany()
db.collection(<collection_name>).insertMany(<documents_array>, <callback_function>)
| Parameter | Description |
|---|---|
| <collection_name> | Name of the MongoDB collection into which the document or documents will be inserted. |
| <document> | Single JavaScript object that has to be inserted as a MongoDB document. |
| <document_array> | Array of JavaScript objects to be inserted as MongoDB documents. |
| <callback_function> | This Node.js Callback Function is called after Node has tried inserting the document or documents, and is ready with the result. The callback function receives error and result object as arguments. |
Current async/await pattern for MongoDB insertOne() in Node.js
Modern Node.js code commonly uses async/await with MongoClient. In this pattern, connect to the server, select the database with client.db(), select the collection with db.collection(), and then call insertOne().
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db("newdb");
const users = db.collection("users");
const result = await users.insertOne({
name: "Roshan",
age: 22,
role: "developer"
});
console.log(`Document inserted with _id: ${result.insertedId}`);
} finally {
await client.close();
}
}
run().catch(console.error);
The insertOne() result contains the generated insertedId. If you do not provide an _id field, MongoDB creates one for the inserted document.
Document inserted with _id: 665f2d7c9b2d4a5f08d8a421
Current async/await pattern for MongoDB insertMany() in Node.js
Use insertMany() when you already have an array of documents to insert into the same collection. The result object includes insertedCount and insertedIds.
const { MongoClient } = require("mongodb");
const uri = "mongodb://127.0.0.1:27017";
const client = new MongoClient(uri);
async function run() {
try {
await client.connect();
const db = client.db("newdb");
const users = db.collection("users");
const docs = [
{ name: "Udat", age: 21 },
{ name: "Karthik", age: 24 },
{ name: "Anil", age: 23 }
];
const result = await users.insertMany(docs);
console.log(`${result.insertedCount} documents inserted`);
console.log(result.insertedIds);
} finally {
await client.close();
}
}
run().catch(console.error);
3 documents inserted
{
'0': ObjectId("665f2ea49b2d4a5f08d8a422"),
'1': ObjectId("665f2ea49b2d4a5f08d8a423"),
'2': ObjectId("665f2ea49b2d4a5f08d8a424")
}
Insert an embedded document into MongoDB from Node.js
A MongoDB document can contain nested objects and arrays. In Node.js, pass the embedded structure as a normal JavaScript object.
const employee = {
name: "Meera",
age: 28,
address: {
city: "Hyderabad",
country: "India"
},
skills: ["Node.js", "MongoDB", "Express"]
};
const result = await db.collection("employees").insertOne(employee);
console.log(result.insertedId);
The nested address object and the skills array are stored as part of the same document. This is useful when the related data is usually read together with the parent document.
Display inserted MongoDB documents after a Node.js insert
After inserting documents, you can read them back with find(). In Node.js, call toArray() if you want the matching documents as an array.
const insertedUsers = await db.collection("users").find({}).toArray();
console.log(insertedUsers);
In mongosh, use find() directly on the collection.
use newdb
db.users.find({})
Example 1 – insertOne() – Insert Document via Node.js
In this example, we will use insertOne() method and insert a document to MongoDB Collection via Node.js program.
node-js-mongodb-insert-document.js
// we create 'users' collection in newdb database
var url = "mongodb://localhost:27017/newdb";
// create a client to mongodb
var MongoClient = require('mongodb').MongoClient;
// make client connect to mongo service
MongoClient.connect(url, function(err, db) {
if (err) throw err;
// db pointing to newdb
console.log("Switched to "+db.databaseName+" database");
// document to be inserted
var doc = { name: "Roshan", age: "22" };
// insert document to 'users' collection using insertOne
db.collection("users").insertOne(doc, function(err, res) {
if (err) throw err;
console.log("Document inserted");
// close the connection to db when you are done with it
db.close();
});
});
Output
$ node node-js-mongodb-insert-document.js
Switched to newdb database
Document inserted
Mongo Shell
> use newdb
switched to db newdb
> show collections
users
> db.users.find({});
{ "_id" : ObjectId("5a127729a415612642e3d6ad"), "name" : "Roshan", "age" : "22" }
>
Example 2 – insertMany() – Insert Many Documents via Node.js
In this example, we will use insertMany() method and insert multiple documents to MongoDB Collection via Node.js program.
node-js-mongodb-insert-many-documents.js
// we create 'users' collection in newdb database
var url = "mongodb://localhost:27017/newdb";
// create a client to mongodb
var MongoClient = require('mongodb').MongoClient;
// make client connect to mongo service
MongoClient.connect(url, function(err, db) {
if (err) throw err;
// db pointing to newdb
console.log("Switched to "+db.databaseName+" database");
// documents to be inserted
var docs = [{ name: "Udat", age: "21" },
{ name: "Karthik", age: "24" },
{ name: "Anil", age: "23" }];
// insert multiple documents to 'users' collection using insertOne
db.collection("users").insertMany(docs, function(err, res) {
if (err) throw err;
console.log(res.insertedCount+" documents inserted");
// close the connection to db when you are done with it
db.close();
});
});
Output
$ node node-js-mongodb-insert-many-documents.js
Switched to newdb database
3 documents inserted
Mongo Shell
> db.users.find({});
{ "_id" : ObjectId("5a127729a415612642e3d6ad"), "name" : "Roshan", "age" : "22" }
{ "_id" : ObjectId("5a1278efecc5062794f4ed8d"), "name" : "Udat", "age" : "21" }
{ "_id" : ObjectId("5a1278efecc5062794f4ed8e"), "name" : "Karthik", "age" : "24" }
{ "_id" : ObjectId("5a1278efecc5062794f4ed8f"), "name" : "Anil", "age" : "23" }
The first entry was from first example, and the rest three have been inserted with this example.
insertOne() vs insertMany() in Node.js MongoDB applications
| Method | Use it when | Useful result fields |
|---|---|---|
insertOne() | You need to add one document to a collection. | insertedId |
insertMany() | You need to add an array of documents to the same collection. | insertedCount, insertedIds |
For a small form submission or a single API request, insertOne() is usually enough. For seed data, imports prepared in memory, or batch inserts from your application code, insertMany() is more direct. For large JSON or CSV files, use MongoDB database tools such as mongoimport instead of writing a custom insert loop.
Common MongoDB insert errors in Node.js
- Connection error: Check whether MongoDB is running and whether the URI points to the correct host, port, and database.
- Duplicate key error: This usually happens when you insert a document with an
_idvalue that already exists in the collection. - Collection name typo: MongoDB may create a new collection when you insert into a collection name that does not already exist, so check the collection spelling carefully.
- Wrong data type: Store numbers as numbers, not strings, when you want numeric comparison and sorting. For example, prefer
age: 22overage: "22". - Connection not closed: In script-style examples, close the client in a
finallyblock after the insert operation is complete.
Reference links for Node.js MongoDB insert operations
- MongoDB Node.js Driver – Insert Documents
- MongoDB Manual – Insert Documents
- MongoDB Database Tools – mongoimport
- MongoDB Tutorial – Learn MongoDB from basics with Examples.
FAQs on inserting MongoDB documents using Node.js
How do you insert a document into a MongoDB collection using Node.js?
Create a MongoClient, connect to MongoDB, select a database and collection, and call insertOne(document). The document is a JavaScript object, and MongoDB stores it as a BSON document.
What is the difference between insertOne() and insertMany() in Node.js MongoDB?
insertOne() inserts one document and returns an insertedId. insertMany() inserts an array of documents and returns fields such as insertedCount and insertedIds.
Can insertOne() create a MongoDB collection automatically?
Yes. If the target collection does not exist, MongoDB can create it during the insert operation. Still, check collection names carefully because a typo can create an unintended collection.
How do you insert an embedded document in MongoDB using Node.js?
Define the nested object inside the main JavaScript object and pass it to insertOne() or include it in the array passed to insertMany(). MongoDB stores nested objects and arrays inside the same document.
How do you display inserted documents in MongoDB?
In Node.js, use collection.find({}).toArray() to read documents into an array. In mongosh, use db.collectionName.find({}) to display matching documents.
Editorial QA checklist for this Node.js MongoDB insert tutorial
- The page explains both
insertOne()andinsertMany()with Node.js examples. - The current async/await MongoDB driver pattern is included before older callback-style examples.
- All newly added code blocks use PrismJS-compatible classes such as
language-javascript,language-bash,syntax, oroutput. - The tutorial answers related insert questions about embedded documents, displaying inserted documents, automatic
_id, andmongoimport. - Official MongoDB documentation links are included for insert operations and import tooling.
Conclusion: inserting one or many MongoDB documents from Node.js
In this Node.js MongoDB tutorial, we learnt how to insert one or more documents into a MongoDB collection using insertOne() and insertMany(). Use insertOne() for a single document, insertMany() for an array of documents, and verify the result with find() in Node.js or mongosh. In the next tutorial, Node.js MongoDB Find, we shall learn to query documents from a MongoDB collection.
TutorialKart.com