Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
MongoDB to sort by subdocument match?
To sort by sub-document match, you can use aggregate framework. Let us first create a collection with documents −
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Chris",
"StudentDetails": [
{
"Age":21,
"StudentScore":91
},
{
"Age":22,
"StudentScore":99
},
{
"Age":21,
"StudentScore":93
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd57e297924bb85b3f48942")
}
> db.sortBySubDocumentsDemo.insertOne(
{
"StudentName": "Robert",
"StudentDetails": [
{
"Age":24,
"StudentScore":78
},
{
"Age":21,
"StudentScore":86
},
{
"Age":23,
"StudentScore":45
}
]
}
);
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd57e4c7924bb85b3f48943")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.sortBySubDocumentsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd57e297924bb85b3f48942"),
"StudentName" : "Chris",
"StudentDetails" : [
{
"Age" : 21,
"StudentScore" : 91
},
{
"Age" : 22,
"StudentScore" : 99
},
{
"Age" : 21,
"StudentScore" : 93
}
]
}
{
"_id" : ObjectId("5cd57e4c7924bb85b3f48943"),
"StudentName" : "Robert",
"StudentDetails" : [
{
"Age" : 24,
"StudentScore" : 78
},
{
"Age" : 21,
"StudentScore" : 86
},
{
"Age" : 23,
"StudentScore" : 45
}
]
}
Following is the query to sort by subdocument match. Here, we are sorting by StudentScore −
> db.sortBySubDocumentsDemo.aggregate([
{$match: { 'StudentDetails.Age': 21 }},
{$unwind: '$StudentDetails'},
{$match: {'StudentDetails.Age': 21}},
{$project: {_id: 0, "StudentName": 1, 'StudentDetails.StudentScore': 1}},
{$sort: { 'StudentDetails.StudentScore': 1 }},
{$limit: 5}
]);
This will produce the following output −
{ "StudentName" : "Robert", "StudentDetails" : { "StudentScore" : 86 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 91 } }
{ "StudentName" : "Chris", "StudentDetails" : { "StudentScore" : 93 } }Advertisements