
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 Query to Sort Subdocuments
Let us create a collection with documents −
> db.demo136.insertOne( ... { ... ... "Name":"Chris", ... "Details":[ ... { ... "Id":"101", ... "EmployeeName":"Mike", ... "EmployeeDetails":[ ... { ... "EmpId":1001, ... "Salary":1000 ... }, ... { ... "EmpId":1002, ... "Salary":2000 ... } ... ] ... }, ... { ... "Id":"102", ... "EmployeeName":"David", ... "EmployeeDetails":[ ... { ... "EmpId":1004, ... "Salary":4000 ... }, ... { ... "EmpId":1005, ... "Salary":5000 ... } ... ] ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e31b15cfdf09dd6d085399f") }
Display all documents from a collection with the help of find() method −
> db.demo136.find();
This will produce the following output −
{ "_id" : ObjectId("5e31b15cfdf09dd6d085399f"), "Name" : "Chris", "Details" : [ { "Id" : "101", "EmployeeName" : "Mike", "EmployeeDetails" : [ { "EmpId" : 1001, "Salary" : 1000 }, { "EmpId" : 1002, "Salary" : 2000 } ] }, { "Id" : "102", "EmployeeName" : "David", "EmployeeDetails" : [ { "EmpId" : 1004, "Salary" : 4000 }, { "EmpId" : 1005, "Salary" : 5000 } ] } ] }
Following is the query to sort subdocuments −
> db.demo136.aggregate([ ... { $unwind: "$Details" }, ... { ... $project: { ... Name: 1, ... Details: 1, ... SalaryTotal: { ... $sum: "$Details.EmployeeDetails.Salary" ... } ... } ... }, ... { $sort: { SalaryTotal: -1 } }, ... { ... $group: { ... _id: "$_id", ... Name: { $first: "$Name" }, ... Details: { $push: "$Details" } ... } ... } ... ]).pretty()
This will produce the following output −
{ "_id" : ObjectId("5e31b15cfdf09dd6d085399f"), "Name" : "Chris", "Details" : [ { "Id" : "102", "EmployeeName" : "David", "EmployeeDetails" : [ { "EmpId" : 1004, "Salary" : 4000 }, { "EmpId" : 1005, "Salary" : 5000 } ] }, { "Id" : "101", "EmployeeName" : "Mike", "EmployeeDetails" : [ { "EmpId" : 1001, "Salary" : 1000 }, { "EmpId" : 1002, "Salary" : 2000 } ] } ] }
Advertisements