- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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