How MongoDB sort by relevance in Node.js ?
Last Updated :
24 Jul, 2024
MongoDB is a popular, open-source NoSQL database that uses a document-oriented data model. It is designed to handle large amounts of data with high performance and scalability and is often used in big data and real-time web applications. In MongoDB, data is stored in BSON (binary JSON) format, which is similar to JSON but is optimized for storage and retrieval. This allows MongoDB to store complex data structures, such as arrays and nested documents, in a more efficient way than traditional relational databases.
In MongoDB, there are two main ways to sort data: using the .find() method with the .sort() function and using the .aggregate() function. Both methods have their own advantages and disadvantages and the choice of method depends on the specific requirements of the application.Â
In this article, we will discuss all the approaches with illustrations and examples.
find() method: Using the .find() method with the .sort() function is a simple and efficient way to sort data in MongoDB. The .find() method is used to retrieve documents from a collection, and the .sort() function is used to sort the retrieved documents.
Syntax:
db.collection.find(query).sort(sortSpecification)
- The ‘query’ is an optional parameter that specifies the query conditions.
- The ‘sortSpecification’ is a JavaScript object that defines the fields to sort on and the sort order. The fields should be the name of the fields in the documents, and the value should be 1 for ascending order or -1 for descending order.
aggregate() method: Using the .aggregate() method is a more powerful way to sort data in MongoDB, as it allows you to group and sort data based on one or more fields. The .aggregate() method takes an array of pipeline stages as its argument, where each stage defines a specific operation to be performed on the data.
Syntax:
db.collection.aggregate(pipeline, options)
- The ‘pipeline’ is an array of pipeline stages. Each stage transforms the documents as they pass through the pipeline.
- The ‘options’ is an optional parameter that specifies additional options for the aggregate operation. It can be a JavaScript object or a query selector string.
Before coming to the examples first we have to set up the data and MongoDB.
MongoDB Database Structure:
>e-comm
- products
Here ‘e-comm’ is a database and ‘products’ is a collection.

Â
And the data inside the products collection is given below:

Â
Setting up the application:
Step 1: Create a Project folder:
mkdir New folder
Step 2: Move to the created project folder and initialize npm init:
npm init
Step 3: To use the aggregate function and find function in Node.js, we first need to install the MongoDB driver for Node.js. This can be done by running the following command in the terminal:
npm install mongodb

;
Project Structure:

Once the driver is installed, we can connect to the MongoDB server and retrieve the data that we want to sort.Â
Example 1: Here is an example of how to connect to a MongoDB server, retrieve the data as well as sort the data from a collection:
JavaScript
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const database = 'e-comm';
async function getData() {
let result = await client.connect();
let db = result.db(database);
let collection = db.collection('products');
collection.find({}, { sort: { price: 1 } })
.toArray(function (err, result) {
if (err) throw err;
console.log(result);
});
}
getData();
Output: To get the output to follow the commands given below:
node index.js
Example 2: In this example, we will see how to sort data in MongoDB using the aggregate function in Node.js in a scenario where there are multiple prices given and we want to sort the data in the relevance of the order of the number of times a price occurs. This will print the data in a reversed sorted order.
JavaScript
const { MongoClient } = require('mongodb');
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
const database = 'e-comm';
async function getData() {
let result = await client.connect();
let db = result.db(database);
let collection = db.collection('products');
collection.aggregate([
{ $group: { _id: "$price", relevance: { $sum: 1 } } },
{ $sort: { relevance: -1 } }
]).toArray(function (err, result) {
if (err) throw err;
console.log(result);
});
}
getData();
Output: To get the output follow the commands given below:
node index.js
In conclusion, sorting data in MongoDB using the aggregate function in Node.js is a powerful feature that allows you to group and sort data based on one or more fields. By understanding the basics of aggregate functions.
Reference: https://www.mongodb.com/docs/manual/reference/operator/aggregation/sort/
Similar Reads
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 Search by id in MongoDB
In MongoDB, each document in a collection is uniquely identified by a field called "_id". This "_id" field serves as the primary key and provides a unique identifier for each document. Searching by ID is a common operation in MongoDB and allows us to retrieve specific documents based on their unique
4 min read
How to Get the Last N Records in MongoDB?
In MongoDB, the developers sometimes encounter the challenge of retrieving the last N records to access real-time information efficiently. To solve this problem, we explore effective methods that fast data retrieval and make it simple for users to access the latest insights easily. In this article,
4 min read
How to work Mongojs module in Node.js ?
Mongojs module is a built-in module in node.js that facilitates the usage of MongoDB with Node.js. It offers almost all the functionality that is provided by the official API of MongoDB and is used extensively by developers across the globe. Follow the steps mentioned below to install mongojs module
3 min read
How to use $group for a MongoDB query in Node.js ?
The $group stage in MongoDB's aggregation framework is a powerful tool for grouping documents by a specified field and performing various operations on the grouped data, such as calculating totals, averages, and other aggregates. When combined with Node.js, this allows for efficient data processing
3 min read
MongoDB Required Constraint using Node.js
Mongoose module is one of the most powerful external modules of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server. Mongoose module provides several functions in order to manipulate the docum
2 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 Aggregation Operations in MongoDB using Node.js?
Aggregation operations in MongoDB allow you to process data records and return computed results. These operations group values from multiple documents, and perform a variety of operations on the grouped data to return a single result. MongoDB's aggregation framework is powerful and flexible, enablin
3 min read
How to Make a Synchronous MongoDB Query in NodeJS?
MongoDB is a popular NoSQL database that is often used in modern web development. It is known for its flexibility, scalability, and ease of use. Node.js, with its non-blocking, event-driven architecture, is a natural fit for MongoDB. However, working with asynchronous code can sometimes be challengi
2 min read
How to add range in the Collection of Mongodb using Node.js ?
Mongoose.module is one of the most powerful external module of the node.js.Mongoose is a MongoDB ODM i.e (Object database Modelling) that used to translate the code and its representation from MongoDB to the Node.js server.Mongoose module provides several functions in order to manipulate the documen
2 min read