TIL — Demystifying MongoDB Sorting Pipelines

MongoDB is a popular NoSQL database known for its flexibility, scalability, and performance. One of the essential features of MongoDB is its aggregation framework, which allows for complex data manipulation and analysis. In this article, we will explore MongoDB’s sorting pipelines, an essential part of the aggregation framework.

What are Sorting Pipelines?

Sorting pipelines in MongoDB are a set of operations that enable you to sort documents in a collection based on specified fields. The $sort stage of the aggregation pipeline allows you to arrange the documents in ascending or descending order based on one or more fields. The syntax for the $sort stage is as follows:

{ $sort: { <field1>: <sort order>, <field2>: <sort order>, ... } }

The <sort order> can be either 1 for ascending order or -1 for descending order.

Basic Sorting

Let’s assume we have a products collection with the following documents:

[
{ "_id": 1, "name": "Keyboard", "price": 50 },
{ "_id": 2, "name": "Mouse", "price": 20 },
{ "_id": 3, "name": "Monitor", "price": 150 },
{ "_id": 4, "name": "Laptop", "price": 800 }
]

To sort the documents by the price field in ascending order, we would use the following code:

const { MongoClient } = require('mongodb');

(async () => {
const client = new MongoClient('mongodb://localhost:27017', { useUnifiedTopology: true });
await client.connect();
const db = client.db('example');
const products = db.collection('products');

const pipeline = [{ $sort: { price: 1 } }];

const sortedProducts = await products.aggregate(pipeline).toArray();

console.log(sortedProducts);
await client.close();
})();

Output

[
{ "_id": 2, "name": "Mouse", "price": 20 },
{ "_id": 1, "name": "Keyboard", "price": 50 },
{ "_id": 3, "name": "Monitor", "price": 150 },
{ "_id": 4, "name": "Laptop", "price": 800 }
]