Read From MongoDB


So in this tutorial, we are going to read document from MongoDB collection using Node.js. If we compare this with MySql then we are going to read record from table. Table in MongoDB are consider as collection and record as document.

Topics Covered 

  • Find One – Find Single Document from Collection
  • Find – Find All Document from Collection

Find One – Find Single Document from Collection

We have lot of documents in a collection, we will match the documents and find the single document out of the multiple documents that we match using findOne().

findone.js

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

MongoClient.connect(url, function (err, db) {

    if (err) throw err;
    var query = {name: 'Jai Sharma'};
    db.collection("customer").find(query, function (err, result) {
        if (err) throw err;
        console.log(result);
        db.close();
    });

});

Run Command:

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

Result:

name: 'Jai Sharma'

Find – Find All Document from Collection

We have many documents in the collection, we will match the documents using findMany() and select all the documents that match and show then all at once.

findall.js

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

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  db.collection("students").find({}).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

Run Command:

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

Result:

Learn More-