Insert Into MongoDB


 Table in MongoDb is know as Collection and record is know as Document. 

So in this tutorial we are going to insert document into MongoDB collection using Node.js.

Topics Covered 

  • Insert One – Insert Single Document in Collection
  • Insert Many – Insert Multiple Document in Collection

Insert One – Insert Single Document in Collection

We have a database with the name of the college and we are going to insert a document in student collection.

 insert.js – insertOne() 

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/college";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var myStudent = { name: "Jai Sharma", address: "E-3, Arera Colony, Bhopal" };
    db.collection("students").insertOne(myStudent, function (err, result) {
        if (err) throw err;
        console.log("1 Recorded Inserted");
        db.close();
    });

});

Run Command:

C:\Users\Your Name>node insert.js

Result:

1 document inserted

Insert Many – Insert Multiple Document in Collection

Insert multiple documents in student collection. We have created an array of myStudent and we are going to pass an array of students into insertMany()

 insertmultiple.js – insertMany() 
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/college";

MongoClient.connect(url, function (err, db) {
    if (err) throw err;
    var myStudent = [
        { name: 'Rohit', address: 'Magnet Brains Bhopal'},
        { name: 'Jai', address: 'Area Colony'},
        { name: 'Roy', address: 'Ashoka Garden'},
        { name: 'Rocky', address: 'MP Nagar'}
      ];
    db.collection("students").insertMany(myStudent, function (err, result) {
        if (err) throw err;
        console.log("Number of documents inserted: " + res.insertedCount);
        db.close();
    });

});

Run Command:

C:\Users\Your Name>node insertmultiple.js

Result:

Number of documents inserted: 4

Conclusion:

I hope that everything is cleared you about the insert process if you still have any problem then do comment below.

Learn More-