Dark Mode
Image

Node.js MongoDB Insert Record

The insertOne method is used to insert record in MongoDB's collection. The first argument of the insertOne method is an object which contains the name and value of each field in the record you want to insert.

Example

(Insert Single record)

Insert a record in "employees" collection.

Advertisement

Create a js file named "insert.js", having the following code:

  1. var MongoClient = require('mongodb').MongoClient;  
  2. var url = "mongodb://localhost:27017/ MongoDatabase";  
  3. MongoClient.connect(url, function(err, db) {  
  4. if (err) throw err;  
  5. var myobj = { name: "Ajeet Kumar", age: "28", address: "Delhi" };  
  6. db.collection("employees").insertOne(myobj, function(err, res) {  
  7. if (err) throw err;  
  8. console.log("1 record inserted");  
  9. db.close();  
  10. });  
  11. });  

Open the command terminal and run the following command:

  1. Node insert.js  

Node.js Insert record 1

Now a record is inserted in the collection.


Insert Multiple Records

You can insert multiple records in a collection by using insert() method. The insert() method uses array of objects which contain the data you want to insert.

Example

Insert multiple records in the collection named "employees".

Create a js file name insertall.js, having the following code:

  1. var MongoClient = require('mongodb').MongoClient;  
  2. var url = "mongodb://localhost:27017/ MongoDatabase";  
  3. MongoClient.connect(url, function(err, db) {  
  4. if (err) throw err;  
  5. var myobj = [     
  6. { name: "Mahesh Sharma", age: "25", address: "Ghaziabad"},  
  7. { name: "Tom Moody", age: "31", address: "CA"},  
  8. { name: "Zahira Wasim", age: "19", address: "Islamabad"},  
  9. { name: "Juck Ross", age: "45", address: "London"}  
  10. ];  
  11. db.collection("customers").insert(myobj, function(err, res) {  
  12. if (err) throw err;  
  13. console.log("Number of records inserted: " + res.insertedCount);  
  14. db.close();  
  15. });  
  16. });  

Open the command terminal and run the following command:

  1. Node insertall.js  

Node.js Insert record 2

You can see here 4 records are inserted.

Comment / Reply From