- 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 Query
Querying is the backbone of any database-driven application. In MongoDB, querying is the process of retrieving specific documents from a collection that match your criteria. When using Node.js with the official mongodb driver, you interact with the database using JSON-like objects, making the transition from JavaScript code to database logic feel seamless and intuitive.
Key Features of MongoDB Query
- Flexible Filters: You aren't limited to simple equality. You can use powerful operators like
$gt(greater than),$in(matches any value in an array), or$regexfor pattern matching. - Projection: This allows you to "shape" your data. Instead of pulling an entire 5MB document, you can request only the
emailandusernamefields, significantly reducing memory and network overhead. - Sorting and Pagination: Built-in methods like
.sort(),.limit(), and.skip()make it easy to build features like "Top 10 High Scores" or "Page 2 of Search Results."
Step 1 Prerequisites
Before you start, ensure you have a local MongoDB instance running (or an Atlas connection string). You will also need to initialize your Node.js project and install the driver.
npm install mongodb
Step 2 Query with Simple Filters
The most common query is searching for documents that match a specific value. The collection.find() method is your primary tool here. It takes a filter object as its first argument.
Example Code
const { MongoClient } = require('mongodb');
// Connection URL and Database Name
const url = 'mongodb://127.0.0.1:27017';
const dbName = 'mydatabase';
async function simpleQuery() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Find documents where name is 'Alice'
// find() returns a Cursor; toArray() converts that cursor into a usable JavaScript array
const result = await collection.find({ name: 'Alice' }).toArray();
console.log('Query Result:', result);
} finally {
// Always close the connection to prevent memory leaks
await client.close();
}
}
simpleQuery().catch(console.error);
Output:
[
{ "_id": 1, "name": "Alice", "age": 28 }
]
find() returns a Cursor, not the data itself. You must use .toArray() or a forEach loop to actually access the documents.
Step 3 Query with Comparison Operators
In real-world apps, you often need ranges—for example, products priced under $50 or users who signed up after a certain date. MongoDB uses operators starting with a $ sign to handle these comparisons.
Example Code
async function queryWithOperators() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Find users older than 30 ($gt stands for Greater Than)
// Other common ones: $lt (less than), $gte (greater or equal), $ne (not equal)
const result = await collection.find({ age: { $gt: 30 } }).toArray();
console.log('Users older than 30:', result);
} finally {
await client.close();
}
}
queryWithOperators().catch(console.error);
Output:
[
{ "_id": 2, "name": "Bob", "age": 35 }
]
collection.findOne(). It returns the object directly instead of a cursor, which is faster and cleaner.
Step 4 Query with Logical Operators
Logical operators like $and, $or, and $nor allow you to combine multiple conditions into a single query. This is essential for building complex search filters.
Example Code
async function queryWithLogicalOperators() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Find users who are either older than 30 OR named 'Alice'
const result = await collection.find({
$or: [
{ age: { $gt: 30 } },
{ name: 'Alice' }
]
}).toArray();
console.log('Logical Query Result:', result);
} finally {
await client.close();
}
}
queryWithLogicalOperators().catch(console.error);
Output:
[
{ "_id": 1, "name": "Alice", "age": 28 },
{ "_id": 2, "name": "Bob", "age": 35 }
]
$and operator only when you need to query the same field multiple times in one statement.
Step 5 Query with Regex
Regular expressions (Regex) are incredibly useful for building search bars where users might only remember the beginning of a name or a partial keyword.
Example Code
async function queryWithRegex() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Find users whose name starts with 'A' (case-insensitive)
// The 'i' flag makes the search case-insensitive
const result = await collection.find({ name: { $regex: '^A', $options: 'i' } }).toArray();
console.log('Regex Query Result:', result);
} finally {
await client.close();
}
}
queryWithRegex().catch(console.error);
Output:
[
{ "_id": 1, "name": "Alice", "age": 28 }
]
Step 6 Query with Projection
Projection is used to filter the fields returned in the result. In a production environment, documents can be huge (e.g., a user profile with dozens of settings). If you only need their display name, use projection to save bandwidth.
Example Code
async function queryWithProjection() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Retrieve only the 'name' field.
// Setting name to 1 includes it; setting _id to 0 excludes it.
const result = await collection.find({}, {
projection: { name: 1, _id: 0 }
}).toArray();
console.log('Projection Query Result:', result);
} finally {
await client.close();
}
}
queryWithProjection().catch(console.error);
Output:
[
{ "name": "Alice" },
{ "name": "Bob" }
]
_id field. For example, { name: 1, age: 0 } will throw an error.
Step 7 Sort and Limit Results
When displaying data to a user, you rarely want to show every single document at once. Sorting and limiting are essential for features like "Latest News" or pagination.
Example Code
async function queryWithSortAndLimit() {
const client = new MongoClient(url);
try {
await client.connect();
const db = client.db(dbName);
const collection = db.collection('users');
// Retrieve 1 user, sorted by age in descending order (-1)
// For ascending order, use 1
const result = await collection.find({})
.sort({ age: -1 })
.limit(1)
.toArray();
console.log('Sorted and Limited Query Result:', result);
} finally {
await client.close();
}
}
queryWithSortAndLimit().catch(console.error);
Output:
[
{ "_id": 2, "name": "Bob", "age": 35 }
]
.limit() with .skip(). For example, to get the second page of 10 results, use .skip(10).limit(10).
Summary
Mastering queries in Node.js allows you to build highly performant and responsive applications. By combining filters, logical operators, and projections, you ensure that your app only processes the data it truly needs. Remember to always close your client connections and use specific methods like findOne() or projection to keep your database interactions efficient.