Nodejs MongoDB sort

sort() method is used along with the find() method in MongoDB in ascending order or descending order based on keyname (field name).

Suppose, You have users collections that have 4 documents.


[
	{
		"_id" : ObjectId("5fdc8b842649b8748d4ec107"),
		"name" : "John",
		"age" : 35
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f86"),
		"name" : "Rom",
		"age" : 31
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f87"),
		"name" : "Mathew",
		"age" : 32
	},
	{
		"_id" : ObjectId("5fdcdb87b6dad382104b0f88"),
		"name" : "Sachin",
		"age" : 38
	}
]

get all the documents in ascending order through {keyname:1} in sort() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).sort({name:1}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 } ]

get all the documents in descending order through {keyname:-1} in sort() method

Firstly create the get_document.js file.


var MongoClient = require('mongodb').MongoClient;

let url="mongodb://localhost:27017/";
var options = {
  useNewUrlParser: true,
  useUnifiedTopology: true,  
}
MongoClient.connect(url,options, function (err, connection_obj) {
  try{
     if (err) throw err;
     var dbo = connection_obj.db("users_management");
     dbo.collection("users").find({}).sort({name:-1}).toArray(function(err, res) {
      if (err) throw err;
       console.log("documents show successfully");
       console.log("result:",res);
       connection_obj.close();
    });

  }catch(err){

    console.log("connection fails");
  
  }

Now, run the get_document.js file.


node get_document.js
Output:-
documents show successfully
result: [ { _id: 5fddc8f7329e1da50a4ec728, name: ‘Sachin’, age: 38 },
{ _id: 5fddc8f7329e1da50a4ec726, name: ‘Rom’, age: 31 },
{ _id: 5fddc8f7329e1da50a4ec727, name: ‘Mathew’, age: 32 },
{ _id: 5fddc8f7329e1da50a4ec725, name: ‘John’, age: 35 } ]