Sort MongoDB Collection by Array value?


To sort MongoDB collection by Array value, use aggregate() along with $sort. Let us create a collection with documents −

> db.demo577.insertOne(
...    {
...
...       "student": {
...          "details": [
...             {
...                Name:"Chris",
...                Score:45
...             },
...             {
...                Name:"Bob",
...                Score:33
...             },
...             {
...                Name:"David",
...                Score:48
...             }
...          ]
...       }
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e916ff1581e9acd78b427ff")
}

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

> db.demo577.find();

This will produce the following output −

{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : [
   { "Name" : "Chris", "Score" : 45 },
   { "Name" : "Bob", "Score" : 33 },
   { "Name" : "David", "Score" : 48 } 
] } }

Following is the query to sort the collection by array value −

> db.demo577.aggregate([
...    {$unwind:"$student"},
...    {$unwind:"$student.details"},
...
...    {$sort:{"student.details.Score":-1}}
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "David", "Score" : 48 } } }
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Chris", "Score" : 45 } } }
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Bob", "Score" : 33 } } }

Updated on: 15-May-2020

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements