Dark Mode
Image

Node.js MongoDB Select Record

The findOne() method is used to select a single data from a collection in MongoDB. This method returns the first record of the collection.

Example

(Select Single Record)

Select the first record from the ?employees? collection.

Advertisement.

Create a js file named "select.js", having the following code:

  1. var http = require('http');  
  2. var MongoClient = require('mongodb').MongoClient;  
  3. var url = "mongodb://localhost:27017/MongoDatabase";  
  4. MongoClient.connect(url, function(err, db) {  
  5.   if (err) throw err;  
  6.   db.collection("employees").findOne({}, function(err, result) {  
  7.     if (err) throw err;  
  8.     console.log(result.name);  
  9.     db.close();  
  10.   });  
  11. });  

Open the command terminal and run the following command:

  1. Node select.js  

Node.js Select record 1


Select Multiple Records

The find() method is used to select all the records from collection in MongoDB.

Example

Select all the records from "employees" collection.

Create a js file named "selectall.js", having the following code:

  1. var MongoClient = require('mongodb').MongoClient;  
  2. var url = "mongodb://localhost:27017/MongoDatabase";  
  3. MongoClient.connect(url, function(err, db) {  
  4.   if (err) throw err;  
  5.   db.collection("employees").find({}).toArray(function(err, result) {  
  6.     if (err) throw err;  
  7.     console.log(result);  
  8.     db.close();  
  9.   });  
  10. });  

Open the command terminal and run the following command:

  1. Node selectall.js  

Node.js Select record 2

You can see that all records are retrieved.

Comment / Reply From