In this tutorial you will learn about the Nodejs MongoDB Find Record and its application with practical example.
Node.js MongoDB Find Record
The findOne() method is used to select a single record from a MongoDB collection. It returns the first record in the given collection.
Example :- Let’s select a single record from “employees” collection.
Step 1:- Let’s, create a node_mongo_findone.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 11 |
var http = require('http'); var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/nodemongo"; MongoClient.connect(url, function(err, db) { if (err) throw err; db.collection("employees").findOne({}, function(err, res) { if (err) throw err; console.log(res.emp_name); db.close(); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mongo_findone.js |
you will see following output on terminal –
Output:-
1 |
Keith |
Node.js MongoDB Select Multiple Record
The find() method is used to select all records from a MongoDB collection. It returns the all record in the given collection.
Example :- Let’s select all record from “employees” collection.
Step 1:- Let’s, create a node_mongo_find.js file and put the following code in it –
1 2 3 4 5 6 7 8 9 10 |
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/nodemongo"; MongoClient.connect(url, function(err, db) { if (err) throw err; db.collection("employees").find({}).toArray(function(err, res) { if (err) throw err; console.log(res); db.close(); }); }); |
Step 2:- Save the code and open the terminal again, and type the following command in order to run the file.
1 |
$ node node_mongo_find.js |
you will see following output on terminal –
Output:-
1 2 3 4 5 6 7 |
[ { _id: 58fdbf5c0ef8a50b4cdd9a74 , emp_name: 'Keith', emp_age: '28', emp_salary: '10000'}, { _id: 58fdbf5c0ef8a50b4cdd9a75 , emp_name: "Alex", emp_age: "25", emp_salary: "5000"}, { _id: 58fdbf5c0ef8a50b4cdd9a76 , emp_name: "John", emp_age: "35", emp_salary: "8000"}, { _id: 58fdbf5c0ef8a50b4cdd9a77 , emp_name: "Steve", emp_age: "28", emp_salary: "7500"}, { _id: 58fdbf5c0ef8a50b4cdd9a78 , emp_name: "Scott", emp_age: "40", emp_salary: "10000"} ] |