Retrieving Documents from MongoDB using Node.js: `findOne()` and `find()` Methods

Learn how to query and retrieve data from MongoDB collections using Node.js. This tutorial explains the `findOne()` and `find()` methods, demonstrating how to select single and multiple documents based on specified criteria, and providing practical examples for efficient data retrieval.



Selecting Documents from a MongoDB Collection Using Node.js

This tutorial explains how to query and retrieve documents from a MongoDB collection using Node.js. MongoDB is a NoSQL, document-oriented database. The `findOne()` method retrieves a single document, while `find()` retrieves multiple documents.

Selecting a Single Document with `findOne()`

The `findOne()` method retrieves a single document from a collection. It returns the first document that matches the query criteria. If no document matches, it returns `null`.


db.collection('collectionName').findOne(query, callback);

The `query` parameter specifies the selection criteria (an empty object `{}` selects the first document). The `callback` function handles the result and any errors.

Example: Retrieving a single document from the `employees` collection:


const MongoClient = require('mongodb').MongoClient;
// ... (database connection) ...
db.collection('employees').findOne({}, (err, result) => {
  if (err) throw err;
  console.log(result); //Prints the first document in the collection.
  db.close();
});

Selecting Multiple Documents with `find()`

To retrieve multiple documents, use the `find()` method. The `find()` method returns a cursor; you use methods like `toArray()` to get all matching documents at once or iterate through them one by one.


db.collection('collectionName').find(query).toArray(callback);

The `query` parameter specifies the selection criteria. An empty object `{}` selects all documents. The `callback` function receives an array of documents.

Example: Retrieving all documents from the `employees` collection:


const MongoClient = require('mongodb').MongoClient;
// ... (database connection) ...
db.collection('employees').find({}).toArray((err, result) => {
  if (err) throw err;
  console.log(result); //Prints all documents.
  db.close();
});