MongoDB aggregate query to sort



To sort, use $match along with aggregate. Let us create a collection with documents −

> db.demo67.insertOne({"StudentAge":23}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e289edf602d9a2ff1828ed8") } > db.demo67.insertOne({"StudentAge":21}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e289ee1602d9a2ff1828ed9") } > db.demo67.insertOne({"StudentAge":24}); {    "acknowledged" : true,    "insertedId" : ObjectId("5e289ee3602d9a2ff1828eda") }

Display all documents from a collection with the help of find() method −

> db.demo67.find();

This will produce the following output −

{ "_id" : ObjectId("5e289edf602d9a2ff1828ed8"), "StudentAge" : 23 } { "_id" : ObjectId("5e289ee1602d9a2ff1828ed9"), "StudentAge" : 21 } { "_id" : ObjectId("5e289ee3602d9a2ff1828eda"), "StudentAge" : 24 }

Following is the query to sort with aggregate in MongoDB −

> db.demo67.aggregate([ ... {$match: {"StudentAge": {$gt: 20} }} ... ,{$sort: {"StudentAge": -1} } ... ]);

This will produce the following output −

{ "_id" : ObjectId("5e289ee3602d9a2ff1828eda"), "StudentAge" : 24 } { "_id" : ObjectId("5e289edf602d9a2ff1828ed8"), "StudentAge" : 23 } { "_id" : ObjectId("5e289ee1602d9a2ff1828ed9"), "StudentAge" : 21 }
Updated on: 2020-03-30T07:29:16+05:30

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements