 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP 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
Sort MongoDB Collection by Array value?
To sort MongoDB collection by Array value, use aggregate() along with $sort. Let us create a collection with documents −
> db.demo577.insertOne( ...    { ... ...       "student": { ...          "details": [ ...             { ...                Name:"Chris", ...                Score:45 ...             }, ...             { ...                Name:"Bob", ...                Score:33 ...             }, ...             { ...                Name:"David", ...                Score:48 ...             } ...          ] ...       } ...    } ... ); {    "acknowledged" : true,    "insertedId" : ObjectId("5e916ff1581e9acd78b427ff") } Display all documents from a collection with the help of find() method −
> db.demo577.find();
This will produce the following output −
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : [    { "Name" : "Chris", "Score" : 45 },    { "Name" : "Bob", "Score" : 33 },    { "Name" : "David", "Score" : 48 } ] } } Following is the query to sort the collection by array value −
> db.demo577.aggregate([ ...    {$unwind:"$student"}, ...    {$unwind:"$student.details"}, ... ...    {$sort:{"student.details.Score":-1}} ... ]); This will produce the following output −
{ "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "David", "Score" : 48 } } } { "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Chris", "Score" : 45 } } } { "_id" : ObjectId("5e916ff1581e9acd78b427ff"), "student" : { "details" : { "Name" : "Bob", "Score" : 33 } } }Advertisements
 