• Node.js Video Tutorials

Node.js - MongoDB Sort



The result of find() query on a collection in a MongoDB database can be arranged in ascending or descending order of a certain field in the Document. The mongodb driver for Node.js has sort() method defined in the Collection object.

To sort the results of a MongoDB query in Node.js, you can use the sort() method. This method allows you to order the returned documents by the values of one or more fields in a certain direction. To sort returned documents by a field in ascending (lowest first) order, use a value of 1. To sort in descending (greatest first) order instead, use -1.

The syntax for ascending order is as follows −

result = col.find(query).sort(field:1);

The syntax for descending sort is as follows −

result = col.find(query).sort(field:-1);

Ascending sort

The following example displays the documents in the products collection in the ascending order of price.

Example

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

async function main(){

   const uri = "mongodb://localhost:27017/";
   const client = new MongoClient(uri);

   try {
      await client.connect();
      await sortdocs(client, "mydb", "products");
   } finally {
      await client.close();
   }
}

main().catch(console.error);
async function sortdocs(client, dbname, colname){
   var mysort = { price: 1 };
   const result = await client.db(dbname).collection(colname).find({}).sort(mysort).toArray();
   result.forEach(element => {
      console.log(element);
   });
}

Output

{
  _id: new ObjectId('6580964f20f979d2e9a72ae9'),
  ProductID: 3,
  Name: 'Router',
  price: 2000
}
{
  _id: new ObjectId('6580964f20f979d2e9a72aea'),
  ProductID: 4,
  Name: 'Scanner',
  price: 5000
}
{
  _id: new ObjectId('6580964f20f979d2e9a72aeb'),
  ProductID: 5,
  Name: 'Printer',
  price: 9000
}
{
  _id: new ObjectId('65809214693bd4622484dce3'),
  ProductID: 1,
  Name: 'Laptop',
  Price: 25000
}
{
_id: new ObjectId('6580964f20f979d2e9a72ae8'),
  ProductID: 2,
  Name: 'TV',
  price: 40000
}

Descending sort

To produce list of documents from products collection in the descending order of name field, change the sortdocs() function to the following −

Example

async function sortdocs(client, dbname, colname){
   var mysort = { Name: -1 };
   const result = await client.db(dbname).collection(colname).find({}).sort(mysort).toArray();
   result.forEach(element => {
      console.log(element);
   });
});

Output

{
  _id: new ObjectId('6580964f20f979d2e9a72ae8'),
  ProductID: 2,
  Name: 'TV',
  price: 40000
}
{
  _id: new ObjectId('6580964f20f979d2e9a72aea'),
  ProductID: 4,
  Name: 'Scanner',
  price: 5000
}
{
  _id: new ObjectId('6580964f20f979d2e9a72ae9'),
  ProductID: 3,
  Name: 'Router',
  price: 2000
}
{
_id: new ObjectId('6580964f20f979d2e9a72aeb'),
  ProductID: 5,
  Name: 'Printer',
  price: 9000
}
{
  _id: new ObjectId('65809214693bd4622484dce3'),
  ProductID: 1,
  Name: 'Laptop',
  Price: 25000
}
Advertisements