How to sort, select and query subdocument in MongoDB?


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

> db.demo236.insertOne({"details":{"Name":"Chris","Age":21}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e419015f4cebbeaebec514c")
}
> db.demo236.insertOne({"details":{"Name":"David","Age":23}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e41901cf4cebbeaebec514d")
}
> db.demo236.insertOne({"details":{"Name":"Bob","Age":24}});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e419023f4cebbeaebec514e")
}

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

> db.demo236.find();

This will produce the following output −

{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "details" : { "Name" : "Chris", "Age" : 21 } }
{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "details" : { "Name" : "David", "Age" : 23 } }
{ "_id" : ObjectId("5e419023f4cebbeaebec514e"), "details" : { "Name" : "Bob", "Age" : 24 } }

Following is the query to sort, select and query subdocument in MongoDB −

>  db.demo236.aggregate(
...   [
...      { $unwind: "$details" },
...      { $project: {
...         Name: '$details.Name',
...         Age: '$details.Age'
...
...      }},
...   { $sort: {Name: -1}}
...]
...);

This will produce the following output −

{ "_id" : ObjectId("5e41901cf4cebbeaebec514d"), "Name" : "David", "Age" : 23 }
{ "_id" : ObjectId("5e419015f4cebbeaebec514c"), "Name" : "Chris", "Age" : 21 }
{ "_id" : ObjectId("5e419023f4cebbeaebec514e"), "Name" : "Bob", "Age" : 24 }

Updated on: 30-Mar-2020

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements