Welcome to The Coding College! In this tutorial, we’ll dive into querying MongoDB documents using Node.js. MongoDB queries allow you to efficiently retrieve and filter data from collections, making it a vital skill for developers building database-driven applications.
Prerequisites
Before you get started, ensure you have:
- MongoDB Installed: Download MongoDB.
- Node.js Installed: Download Node.js.
- MongoDB Driver Installed: Install it using:
npm install mongodb
Step 1: Setup MongoDB Connection
Create a file queryData.js
and set up the connection to MongoDB:
const { MongoClient } = require('mongodb');
// MongoDB connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database and Collection Names
const dbName = 'myNewDatabase';
const collectionName = 'users';
async function connectToDatabase() {
try {
// Connect to MongoDB
await client.connect();
console.log('Connected to MongoDB.');
return client.db(dbName).collection(collectionName);
} catch (err) {
console.error('Database connection error:', err.message);
}
}
Step 2: Query Documents
1. Query All Documents
To retrieve all documents in a collection, use the find()
method:
async function queryAllDocuments() {
const collection = await connectToDatabase();
const documents = await collection.find().toArray();
console.log('All Documents:', documents);
}
queryAllDocuments();
2. Query with Filters
Use filters to retrieve specific documents. For example, find users with an age
greater than 25:
async function queryWithFilters() {
const collection = await connectToDatabase();
const filter = { age: { $gt: 25 } };
const documents = await collection.find(filter).toArray();
console.log('Filtered Documents:', documents);
}
queryWithFilters();
3. Query with Multiple Conditions
Combine conditions using MongoDB’s logical operators. Example: Find users aged between 20 and 30:
async function queryWithMultipleConditions() {
const collection = await connectToDatabase();
const filter = {
$and: [{ age: { $gte: 20 } }, { age: { $lte: 30 } }],
};
const documents = await collection.find(filter).toArray();
console.log('Documents with Multiple Conditions:', documents);
}
queryWithMultipleConditions();
4. Query Using Logical Operators
Find users with either a specific name or email:
async function queryWithLogicalOperators() {
const collection = await connectToDatabase();
const filter = {
$or: [{ name: 'John Doe' }, { email: '[email protected]' }],
};
const documents = await collection.find(filter).toArray();
console.log('Documents Matching Logical Operators:', documents);
}
queryWithLogicalOperators();
5. Query with Regular Expressions
Find users whose names start with “A”:
async function queryWithRegex() {
const collection = await connectToDatabase();
const filter = { name: { $regex: '^A', $options: 'i' } };
const documents = await collection.find(filter).toArray();
console.log('Documents Matching Regex:', documents);
}
queryWithRegex();
Step 3: Use Projections to Limit Fields
Projections allow you to retrieve only specific fields, reducing data transfer and improving performance:
async function queryWithProjection() {
const collection = await connectToDatabase();
const filter = {};
const projection = { name: 1, email: 1 }; // Include only name and email
const documents = await collection.find(filter, { projection }).toArray();
console.log('Projected Documents:', documents);
}
queryWithProjection();
Step 4: Combine Query with Sorting and Limiting
You can combine queries with sorting and limiting for more refined results. Example: Find the first 3 youngest users:
async function queryWithSortAndLimit() {
const collection = await connectToDatabase();
const filter = {};
const documents = await collection
.find(filter)
.sort({ age: 1 }) // Sort by age in ascending order
.limit(3) // Limit to 3 documents
.toArray();
console.log('Sorted and Limited Documents:', documents);
}
queryWithSortAndLimit();
Step 5: Delete Retrieved Data
To delete documents after querying, you can use the deleteOne()
or deleteMany()
methods:
async function deleteQueriedData() {
const collection = await connectToDatabase();
const filter = { name: 'John Doe' }; // Specify the condition
const result = await collection.deleteOne(filter);
console.log(`Deleted ${result.deletedCount} document(s).`);
}
deleteQueriedData();
Output Example
When running these scripts, you might see outputs like this:
Connected to MongoDB.
All Documents: [
{ _id: ObjectId("64e12345abcd6789ef123456"), name: 'John Doe', age: 30, email: '[email protected]' },
{ _id: ObjectId("64e12345abcd6789ef123457"), name: 'Alice', age: 25, email: '[email protected]' }
]
Best Practices
- Indexing: Index frequently queried fields to optimize performance.
- Validation: Validate query inputs to avoid injection attacks.
- Error Handling: Always handle exceptions and log errors for debugging.
- Environment Variables: Use
.env
files to secure sensitive information like connection URLs. - Pagination: Use
skip()
andlimit()
for paginated results in larger datasets.
Conclusion
Querying MongoDB with Node.js provides flexibility and power to retrieve and filter data effectively. By mastering these techniques, you can build dynamic and efficient database-driven applications.
Explore more tutorials at The Coding College, and take your programming skills to the next level!