Node JS - Node js MongoDB Select Record - MongoDB - Node - Node JS tutorial - webnode
Related nodejs article tags - node js - node js tutorial - node js examples
How to Select Record of MongoDB in Node.js?
- In node.js select record is used to select a data from a table in mongoDB
- This method returns the first record of the collection.

Select Single Record
- The findOne() method is used to select a single data from a collection in MongoDB.
- To select data from a table in MongoDB, we can use the findOne() method.
- The first parameter of the findOne() method is a query object.

Learn Node js - node js Tutorial - node-js mongodb select data - - node - Node js Examples
Example
- Select the first record from the employees collection. Create a js file named "select.js", having the following code:
Related nodejs article tags - node js - node js tutorial - node js examples
select.js
var http = require('http');
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MongoDatabase";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("employees").findOne({}, function(err, result) {
if (err) throw err;
console.log(result.name);
db.close();
});
});
Open the command terminal and run the following command: Node select.js
Related nodejs article tags - node js - node js tutorial - node js examples
Output:

Learn Node js - node js Tutorial - select single record in node.js mongodb - node - Node js Examples
Select Multiple Records
- The find() method is used to select all the records from collection in MongoDB.
- To select data from a table in MongoDB, we can also use the find() method.
- The find() method returns all occurrences in the selection.
- The first parameter of the find() method is a query object.
Example
- Select all the records from "employees" collection. Create a js file named "selectall.js", having the following code:
Related nodejs article tags - node js - node js tutorial - node js examples
selectall.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/MongoDatabase";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection("employees").find({}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
Open the command terminal and run the following command: Node selectall.js
Related nodejs article tags - node js - node js tutorial - node js examples
Output

Learn Node js - node js Tutorial - multiple records in node.js mongodb select record - node - Node js Examples