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 nested array?
To sort nested array in MongoDB, use $sort. Let us create a collection with documents −
> db.demo505.insertOne(
... {
... "details": [
... {
... Name:"Chris",
... "Score":58
... }, {
...
... Name:"Bob",
... "Score":45
... }, {
...
... Name:"John",
... "Score":68
... }, {
...
... Name:"David",
... "Score":46
... }
... ]
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5e882a6b987b6e0e9d18f574")
}
Display all documents from a collection with the help of find() method −
> db.demo505.find();
This will produce the following output −
{ "_id" : ObjectId("5e882a6b987b6e0e9d18f574"), "details" : [
{ "Name" : "Chris", "Score" : 58 },
{ "Name" : "Bob", "Score" : 45 },
{ "Name" : "John", "Score" : 68 },
{ "Name" : "David", "Score" : 46 }
] }
Following is the query to sort nested array −
> db.demo505.aggregate([
... { $unwind: "$details" },
... { $sort: { "details.Score": 1 } },
... { $group: { _id: "$_id", details: { $push: "$details" } } }
... ]);
This will produce the following output −
{ "_id" : ObjectId("5e882a6b987b6e0e9d18f574"), "details" : [
{ "Name" : "Bob", "Score" : 45 },
{ "Name" : "David", "Score" : 46 },
{ "Name" : "Chris", "Score" : 58 },
{ "Name" : "John", "Score" : 68 }
] }Advertisements