- Node.js Tutorial
- NodeJS Home
- NodeJS Introduction
- NodeJS Setup
- NodeJS First App
- NodeJS REPL
- NodeJS Command Line
- NodeJS NPM
- NodeJS Callbacks
- NodeJS Events
- NodeJS Event-Loop
- NodeJS Event-Emitter
- NodeJS Global-Objects
- NodeJS Console
- NodeJS Process
- NodeJS Buffers
- NodeJS Streams
- Node.js File Handling
- Node.js File System
- Node.js Read/Write File
- Working with folders in Node.js
- HTTP and Networking
- Node.js HTTP Module
- Anatomy of an HTTP Transaction
- Node.js MongoDB
- MongoDB Get Started
- MongoDB Create Database
- MongoDB Create Collection
- MongoDB Insert
- MongoDB Find
- MongoDB Query
- MongoDB Sort
- MongoDB Delete
- MongoDB Update
- MongoDB Limit
- MongoDB Join
- Node.js MySQL
- MySQL Get Started
- MySQL Create Database
- MySQL Create Table
- MySQL Insert Into
- MySQL Select From
- MySQL Where
- MySQL Order By
- MySQL Delete
- MySQL Update
- MySQL Join
- Node.js Modules
- Node.js Modules
- Node.js Built-in Modules
- Node.js Utility Modules
- Node.js Web Module
- Node.js Advanced
- Node.js Debugger
- Node.js Scaling Application
- Node.js Packaging
- Node.js Express Framework
- Node.js RESTFul API
- Node.js Useful Resources
- Node.js Useful Resources
- Node.js Discussion
Node.js MongoDB Find
The find method in MongoDB allows you to query documents in a collection based on specific criteria. With Node.js, you can use the mongodb driver to perform powerful and efficient queries.
Key Features of Find Operation
- Flexible Querying: Supports complex filters using key-value pairs.
- Cursor-Based Results: Returns a cursor for efficient iteration over large datasets.
- Projection Support: Fetch specific fields to optimize performance.
Step 1 Prerequisites
Ensure MongoDB is running, and the mongodb package is installed in your project.
npm install mongodb
Step 2 Retrieve All Documents
To fetch all documents from a collection, use an empty filter {}.
Example Code
const { MongoClient } = require('mongodb');
// Connection URL and Database Name
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';
async function findAllDocuments() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Retrieve all documents
const documents = await collection.find({}).toArray();
console.log('Documents:', documents);
} finally {
await client.close();
}
}
findAllDocuments().catch(console.error);
Output:
[
{ "_id": 1, "name": "Alice", "age": 28 },
{ "_id": 2, "name": "Bob", "age": 32 }
]
Step 3 Query with Filters
Specify a filter object to retrieve matching documents.
Example Code
async function findWithFilters() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Retrieve documents where age is greater than 30
const filter = { age: { $gt: 30 } };
const documents = await collection.find(filter).toArray();
console.log('Filtered Documents:', documents);
} finally {
await client.close();
}
}
findWithFilters().catch(console.error);
Output:
[
{ "_id": 2, "name": "Bob", "age": 32 }
]
Step 4 Use Projection
Projection specifies the fields to include or exclude in the result.
Example Code
async function findWithProjection() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Retrieve documents with only 'name' field
const projection = { projection: { name: 1, _id: 0 } };
const documents = await collection.find({}, projection).toArray();
console.log('Projected Documents:', documents);
} finally {
await client.close();
}
}
findWithProjection().catch(console.error);
Output:
[
{ "name": "Alice" },
{ "name": "Bob" }
]
Step 5 Iterate Using Cursor
For large datasets, iterate through the cursor instead of loading all results into memory.
Example Code
async function iterateWithCursor() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Get a cursor for documents
const cursor = collection.find({});
while (await cursor.hasNext()) {
const document = await cursor.next();
console.log('Document:', document);
}
} finally {
await client.close();
}
}
iterateWithCursor().catch(console.error);
Output:
Document: { _id: 1, name: 'Alice', age: 28 }
Document: { _id: 2, name: 'Bob', age: 32 }
Step 6 Limit and Sort Results
Use the limit and sort methods to control the output.
Example Code
async function findWithLimitAndSort() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Retrieve 1 document sorted by age in descending order
const documents = await collection.find({})
.sort({ age: -1 })
.limit(1)
.toArray();
console.log('Limited and Sorted Documents:', documents);
} finally {
await client.close();
}
}
findWithLimitAndSort().catch(console.error);
Output:
[
{ "_id": 2, "name": "Bob", "age": 32 }
]
Summary
The find method in Node.js with MongoDB provides robust querying capabilities. Using filters, projections, cursors, and additional methods like limit and sort, you can retrieve and manage data effectively. These features allow for flexible and optimized database queries in your applications.