Node.js – Insert Document(s) to MongoDB Collection

We can insert one or more documents to MongoDB collection through Node.js program using insertOne() and insertMany() methods.

In this tutorial, we shall learn to insert one or more documents to MongoDB Collection from Node.js Application, using insertOne() and insertMany() method respectively, with examples.

Steps – Insert Documents to MongoDB Collection via 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 insertMay() 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>)
ParameterDescription
<collection_name>Name of the new MongoDB Collection, that we would like to create
<document>Single document that has to be inserted to MongoDB Collection
<document_array>Array of documents to be inserted to MongoDB Collection
<callback_function>This Node.js Callback Function is called after Node has tried creating a collection, and ready with the result. The callback function receives error and result object as arguments.

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.

Reference

MongoDB Tutorial – Learn MongoDB from basics with Examples.

Conclusion

In this Node.js MongoDB tutorial : Node.js – Insert Document(s) to MongoDB Collection, we have learnt to insert one or more documents to MongoDB Collection using insertOne() and insertMany() methods, from Node.js Application using mongodb package. In our next tutorial – Node.js MongoDB Find, we shall learn to query documents from MongoDB Collection.