
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
Sort Array in MongoDB Query and Project All Fields
To sort array, use $sort. For projection, use $project in MongoBD aggregate(). Let us create a collection with documents −
> db.demo252.insertOne( ... {"Values" : [ { "v1" : 20, "v2" :30 }, { "v1" : 20, "v2" : 20 }, { "v1" : 10, "v2" : 7 } ] } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e46c2761627c0c63e7dba78") }
Display all documents from a collection with the help of find() method −
> db.demo252.find();
This will produce the following output −
{ "_id" : ObjectId("5e46c2761627c0c63e7dba78"), "Values" : [ { "v1" : 20, "v2" : 30 }, { "v1" : 20, "v2" : 20 }, { "v1" : 10, "v2" : 7 } ] }
Following is the query to sort array and project all fields with aggregate() −
> db.demo252.aggregate([ ... { "$unwind": "$Values"}, ... { "$sort": {"Values.v2":1, "Values.v1": 1}}, ... { "$group": { ... "_id": { ... "_id": "$_id" ... ... }, ... "st": { "$push":"$Values"} ... }}, ... { "$project": { ... "_id": "$_id._id", ... "Values": "$st" ... }} ...]);
This will produce the following output −
{ "_id" : ObjectId("5e46c2761627c0c63e7dba78"), "Values" : [ { "v1" : 10, "v2" : 7 }, { "v1" : 20, "v2" : 20 }, { "v1" : 20, "v2" : 30 } ] }
Advertisements