NodeJS – select data from mongoDB collection

Suppose we have a collection in MongoDB database, We want to select data from collection then we can do like the program below.

Suppose we have a collection ( Like table in Relational DBMS)  named grades and this collection is in course database.   Grades collection contains fields like _id, student, grade and so on…  now query is that we want to select students whose grade is 100. 

To do this we first need to connect to MongoDB database server from NodeJs script. For connection to database server we need to include mongodb package. If it id not already installed then use command npm install mongodb, it will install mongodn package.

We are using MongoClient in in mongoDB package.

After including package from mongoDB now we we will connect to our desired database that is course database on localhost

Lines above will connect to local mongodb database.  MongoClient.connect function will require two arguments

one is database server address  with database name that is

‘mongodb://localhost:27017/course’  

Second argument is callback function that returns err  in case it is not able to connect to database server, second argument is db object if database connection is successful. In case of error program will terminate using this line of code

Next we will define a query to restrict results or a where clause in terms of RDBMS.

This query is defining a restriction that select records with grade = 100.

Next line we are telling which fields we want to select like in Relational DB we mention column names after select keywords

here projection variable has a json object that contains student:1 and _id:0. By default in mongoDB _id field is selected with every query that is selecting data from db. To suppress or not to be included in selected fields we specify _id:0. student:1 means we only want to see data for student column from the collection and do not want to select any other column. For _id we need to tell db that ignore this field.

In the line above db object will  go to the grades collection and using find method with two arguments of query and projection will select records and then will convert to an array using toArray function. toArray function has a callback function that accepts two arguments one is err that is thrown using if statement below  in case any errors occurs, docs are the records returned of query executes successful.

Next we will just loop through the records and show in console using foreach loop and in foreach  there will be each document from collection that we will  show using console.log function.

Complete Node JS script is below

 

Comments

  1. By Bert

    Reply

    • By Gulraiz Iqbal

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.