MongoDB query to sort nested array?

MongoDBDatabaseBig Data Analytics

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 } 
] }
raja
Published on 13-May-2020 06:28:57
Advertisements