Performing complex queries in MongoDB with Node.js
Last Updated :
04 Jul, 2024
MongoDB is a popular NoSQL database known for its flexibility and scalability. When working with the MongoDB in the Node.js application. We often need to perform complex queries to retrieve or manipulate the data effectively. This article will guide you through the various approaches to performing complex queries in MongoDB using Node.js.
Performing complex queries in MongoDB with Node.js
1. Basic Query:
The basic query can retrieve the documents that match the specific criteria.
Syntax:
// Find documents where the 'age' is 25
db.collection('users').find({ age: 25 }).toArray((err, result) => {
if (err) throw err;
console.log(result);
});
2. Range Query:
It can be range the queries use comparison operators such as $gt, $lt, $lte.
Syntax:
// Find documents where the 'age' is greater than 25
db.collection('users').find({ age: { $gt: 25 } }).toArray((err, result) => {
if (err) throw err;
console.log(result);
});
3. Logical Query:
The logical queries can combine the multiple conditions using operators like $and, $or and $not.
Syntax:
// Find documents where the 'age' is greater than 25 and 'city' is 'New York'
db.collection('users')
.find({ $and: [{ age: { $gt: 25 } }, { city: 'New York' }] })
.toArray((err, result) => {
if (err) throw err;
console.log(result);
});
4. Aggregation Framework:
The aggregation framework that can allows for the advanced data processing and transformation using the pipeline approach.
Syntax:
// Group users by 'city' and calculate the average age
db.collection('users')
.aggregate([ { $group: { _id: "$city", averageAge: { $avg: "$age" } } }])
.toArray((err, result) => {
if (err) throw err;
console.log(result);
});
Steps to performing complex queries in MongoDB with Nodejs.
Step 1: Initialize the New Node.js Project
npm init -y
Step 2: Install Required Modules
npm install mongodb
Project Structure
Folder Structure
JavaScript
// CreateCollection.js
const { MongoClient } = require('mongodb');
async function createCollection() {
const uri = "MongoDB URI";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db('testdb');
const users = [
{ name: "Alice", age: 30, city: "New York" },
{ name: "Bob", age: 25, city: "San Francisco" },
{ name: "Charlie", age: 35, city: "New York" },
{ name: "David", age: 28, city: "Los Angeles" },
{ name: "Eve", age: 25, city: "San Francisco" }
];
await db
.collection('users')
.insertMany(users);
console.log("Collection created and populated with sample data");
} finally {
await client.close();
}
}
createCollection()
.catch(console.error);
JavaScript
// index.js
const { MongoClient } = require('mongodb');
async function main() {
const uri = "MongoDB URI";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });
try {
await client.connect();
const db = client.db('testdb');
// Basic Query
const basicQueryResult = await db
.collection('users').find({ age: 25 })
.toArray();
console.log("Basic Query Result:", basicQueryResult);
// Range Query
const rangeQueryResult = await db
.collection('users')
.find({ age: { $gt: 25 } })
.toArray();
console.log("Range Query Result:", rangeQueryResult);
// Logical Query
const logicalQueryResult = await db
.collection('users')
.find({ $and: [{ age: { $gt: 25 } }, { city: 'New York' }] })
.toArray();
console.log("Logical Query Result:", logicalQueryResult);
// Aggregation Framework
const aggregationResult = await db
.collection('users')
.aggregate([
{ $group: { _id: "$city", averageAge: { $avg: "$age" } } }
]).toArray();
console
.log("Aggregation Result:", aggregationResult);
} finally {
await client.close();
}
}
main().catch(console.error);
XML
{
"name": "mongodb-queries",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node index.js",
"setup": "node createCollection.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"mongodb": "^6.8.0"
}
}
Step 3: Setup the Collection
We can run the below command to create and populate the MongoDB collection.
npm run setup
Performing complex queries in MongoDB with Node.jsStep 8: Execute the Queries
we can run the below command to execute the queries and see the below output.
npm start
Performing complex queries in MongoDB with Node.jsOutput:
(node:8400) [MONGODB DRIVER] Warning: useNewUrlParser is a deprecated option: useNewUrlParser has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
(Use `node --trace-warnings ...` to show where the warning was created)
(node:8400) [MONGODB DRIVER] Warning: useUnifiedTopology is a deprecated option: useUnifiedTopology has no effect since Node.js Driver version 4.0.0 and will be removed in the next major version
Basic Query Result: [
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5be'),
name: 'Bob',
age: 25,
city: 'San Francisco'
},
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5c1'),
name: 'Eve',
age: 25,
city: 'San Francisco'
}
]
Range Query Result: [
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5bd'),
name: 'Alice',
age: 30,
city: 'New York'
},
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5bf'),
name: 'Charlie',
age: 35,
city: 'New York'
},
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5c0'),
name: 'David',
age: 28,
city: 'Los Angeles'
}
]
Logical Query Result: [
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5bd'),
name: 'Alice',
age: 30,
city: 'New York'
},
{
_id: new ObjectId('6682d2bbe5ac9f7db37cc5bf'),
name: 'Charlie',
age: 35,
city: 'New York'
}
]
Aggregation Result: [
{ _id: 'New York', averageAge: 32.5 },
{ _id: 'San Francisco', averageAge: 25 },
{ _id: 'Los Angeles', averageAge: 28 }
]
Conclusion
By the following this article, we can effectively perform the complex queries in the MongoDB using Node.js and leveraging the various query techniques and the aggregation framework to handle the advanced data processing tasks.
Similar Reads
How to Perform Geospatial Queries in MongoDB using Node.js? A geospatial query involves searching for data based on geographic locations. It allows developers to identify and analyze data associated with specific coordinates or within a defined proximity of a given point. In a geospatial query, we can define a geographic shape, such as a point, line, or poly
6 min read
How to Perform Text Search in MongoDB using Node.js? MongoDB is an open-source, cross-platform, No-SQL database that stores data in documents, which contain data in the form of key-value pairs. In this article, we will learn about how to perform text-based searches in MongoDB using node.js. Prerequisites Node.jsMongoDBMongoDB Atlas Connect with Applic
5 min read
How To Perform a Find Operation With Sorting In MongoDB Using Node.js? Performing a find operation with sorting in MongoDB using Node.js is a common task for developers working with databases. This guide will walk you through the process step-by-step, including setting up a MongoDB database, connecting to it using Node.js, performing a find operation, and sorting the r
3 min read
How to Perform Query Optimization in MongoDB? MongoDB is a popular NoSQL database that offers high performance, high availability, and easy scalability. However, like any database, query performance can degrade if not properly optimized. This article will guide you through several techniques to optimize your MongoDB queries, ensuring they run e
3 min read
How to Perform a findOne Operation in MongoDB using Node.js? The findOne operation in MongoDB is used to get a single document from the collection if the given query matches the collection record. While using findOne, if more than one record is there with the exact same match, then it will return the very first one. We will use this operation if we need to fe
4 min read
How to Perform a Find Operation with Limit and Skip in MongoDB using Node.js? In MongoDB, the find operation is used to query the database and retrieve documents that match a specified criterion. Using limit and skip along with find allows for efficient pagination of results. limit specifies the maximum number of documents to return, while skip specifies the number of documen
3 min read