Open In App

How MongoDB sort by relevance in Node.js ?

Last Updated : 16 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • index.js

Javascript




const { MongoClient } = require('mongodb');
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.

  • index.js

Javascript




const { MongoClient } = require('mongodb');
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/



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads