English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this Node.js tutorial, we will use the insertOne() and insertMany() methods separately, and through examples, learn how to insert one or more documents into a MongoDB Collection from a Node.js application.
The following is a step-by-step guide with an example showing how to insert a document from a Node.js application into a MongoDB Collection.
Start the MongoDB service. Run the following command to start the MongoDB service
sudo service mongod start
Get the basic URL of the MongoDB service. A simple trick to find out the basic URL of the MongoDB service is to open the terminal and run the Mongo Shell.
Terminal - 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]
When the Mongo Shell starts, it echoes the basic URL of MongoDB.
mongodb://127.0.0.1:27017
Prepare the complete URL. Attach the name of the database you want to connect to (for example, newdb) to the basic URL.
mongodb://127.0.0.1:27017/newdb
Create a MongoClient.
var MongoClient = require('mongodb').MongoClient;
Connect to the MongoDB server with the help of the URL.
MongoClient.connect(url, <callback_function>);
Once the MongoClient attempts to establish a connection, the callback function will receive the error and db object as parameters.
If the connection is successful, the db object points to the database newdb.
Insert the document into the specified MongoDB collection. The syntax for the insertOne() and insertMany() methods used to insert a document into a collection in MongoDB from Node.js is as follows.
insertOne()
db.collection(<collection_name>).insertOne(<document>, <callback_function>)
insertMany()
db.collection(<collection_name>).insertMany(<documents_array>, <callback_function>)
Parameter Description:
<collection_name> - The name of the new MongoDB collection we want to create
<document> - Single document to be inserted into the MongoDB Collection
<document_array> - Document array to be inserted into the MongoDB Collection
<callback_function> - After Node attempts to create a collection and prepare the result, this Node.js callback function will be called. The callback function receives an error and a result object as parameters.
// We create the "users" collection in the newdb database var url = "mongodb://localhost:27017/newdb"; // Create a client to mongodb var MongoClient = require('mongodb').MongoClient; // Make the client connect to the mongo service MongoClient.connect(url, function(err, db) { if (err) throw err; // db points to newdb console.log("Switched to ",+db.databaseName+" database");}} // File to be inserted var doc = { name: "Roshan", age: "22}; // Use insertOne to insert the document into the "users" collection db.collection("users").insertOne(doc, function(err, res) { if (err) throw err; console.log("Document inserted"); // Close the connection with db after completion db.close(); }); });
Output Result
$ 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" } >
// We create the "users" collection in the newdb database var url = "mongodb://localhost:27017/newdb"; // Create a client to mongodb var MongoClient = require('mongodb').MongoClient; // Make the client connect to the mongo service MongoClient.connect(url, function(err, db) { if (err) throw err; // db points to newdb console.log("Switched to ",+db.databaseName+" database");}} // File to be inserted var docs = [{ "name": "Udat", "age": "21" }, {"name": "Karthik", "age": "24" }, {"name": "Anil", "age": "23" }]; // Insert multiple documents into the "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 with db after completion db.close(); }); });
Output Result
$ 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 comes from the first example, and the other three have been inserted with this example.
In this Node.js MongoDB tutorial: Node.js – Insert Document(s) into MongoDB CollectionWe learned how to use the mongodb package to insert one or more documents into the MongoDB Collection using the insertOne() and insertMany() methods in the Node.js application. In our next tutorial – Node.js MongoDB Find, we will learn how to query documents from the MongoDB Collection.