MongoDB query to sort nested array?


To sort nested array in MongoDB, use $sort. Let us create a collection with documents −

> db.demo505.insertOne(
... {
...    "details": [
...    {
...       Name:"Chris",
...       "Score":58
...    }, {
...
...          Name:"Bob",
...          "Score":45
...       }, {
...
...             Name:"John",
...             "Score":68
...       }, {
...
...          Name:"David",
...          "Score":46
...       }
...    ]
... }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e882a6b987b6e0e9d18f574")
}

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

> db.demo505.find();

This will produce the following output −

{ "_id" : ObjectId("5e882a6b987b6e0e9d18f574"), "details" : [
   { "Name" : "Chris", "Score" : 58 },
   { "Name" : "Bob", "Score" : 45 },
   { "Name" : "John", "Score" : 68 },
   { "Name" : "David", "Score" : 46 }
] }

Following is the query to sort nested array −

> db.demo505.aggregate([
...    { $unwind: "$details" },
...    { $sort: { "details.Score": 1 } },
...    { $group: { _id: "$_id", details: { $push: "$details" } } }
... ]);

This will produce the following output −

{ "_id" : ObjectId("5e882a6b987b6e0e9d18f574"), "details" : [
   { "Name" : "Bob", "Score" : 45 },
   { "Name" : "David", "Score" : 46 },
   { "Name" : "Chris", "Score" : 58 },
   { "Name" : "John", "Score" : 68 } 
] }

Updated on: 13-May-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements