Working with MongoDB $sort for sub array document


For sub array document in MongoDB, use aggregate along with $sort. Let us first create a collection with documents −

> db.demo23.insertOne(
...{
...
...    "StudentDetails" : [{
...       "Name" : "David",
...       "Age" : 23,
...
...    }, {
...          "Name" : "Adam",
...          "Age" : 24,
...       }]
...    }
... );
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e14c3eb22d07d3b95082e71")
}

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

> db.demo23.find().pretty()

This will produce the following output −

{
   "_id" : ObjectId("5e14c3eb22d07d3b95082e71"),
   "StudentDetails" : [
      {
         "Name" : "David",
         "Age" : 23
      },
      {
         "Name" : "Adam",
         "Age" : 24
      }
   ]
}

Here is the query to work with $sort for sub array document −

> db.demo23.aggregate([
... { "$unwind" : "$StudentDetails"} ,
... { "$sort" : { "StudentDetails.Name" : 1}},
... { "$match" : { }} ,
... { "$group" : { "StudentDetails" : { "$push" : { "Name" : "$StudentDetails.Name"}} , "_id" : null}} ,
... { "$project" : { "_id" : 0 , "StudentDetails" : 1}}
... ]);

This will produce the following output −

{ "StudentDetails" : [ { "Name" : "Adam" }, { "Name" : "David" } ] }

Updated on: 02-Apr-2020

525 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements