- 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 the MongoDB documents in ascending order with aggregation?
Use $sort in MongoDB aggregation. Let us create a collection with documents −
> db.demo652.insertOne({ ... value:10, ... "details" : [{ ... "ProductName" : "Product-1", ... "ProductQuantity" : 8, ... "ProductPrice" : 500 ... }, { ... "ProductName" : "Product-2", ... "ProductQuantity" : 7, ... "ProductPrice" : 500 ... ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9f0730e3c3cd0dcff36a62") } > > db.demo652.insertOne({ ... value:5, ... "details" : [{ ... "ProductName" : "Product-1", ... "ProductQuantity" : 8, ... "ProductPrice" : 500 ... }, { ... "ProductName" : "Product-2", ... "ProductQuantity" : 7, ... "ProductPrice" : 500 ... ... }] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e9f0740e3c3cd0dcff36a63") }
Display all documents from a collection with the help of find() method −
> db.demo652.find();
This will produce the following output −
{ "_id" : ObjectId("5e9f0730e3c3cd0dcff36a62"), "value" : 10, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] } { "_id" : ObjectId("5e9f0740e3c3cd0dcff36a63"), "value" : 5, "details" : [ { "ProductName" : "Product-1", "ProductQuantity" : 8, "ProductPrice" : 500 }, { "ProductName" : "Product-2", "ProductQuantity" : 7, "ProductPrice" : 500 } ] }
Following is the query to sort in ascending order −
> db.demo652.aggregate([{ ... "$unwind": "$details" ... }, { ... "$match": {} ... }, { ... "$group": { ... "ProductPrice": { ... "$first": "$value" ... }, ... "details": { ... "$push": { ... "ProductName": "$details.ProductName" ... } ... }, ... "_id": "$_id" ... } ... }, { ... "$sort": { ... "ProductPrice": 1 ... } ... }, { ... "$project": { ... "_id": 0, ... "ProductPrice": 1, ... "details": 1 ... } ... }]).pretty()
This will produce the following output −
{ "ProductPrice" : 5, "details" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" } ] } { "ProductPrice" : 10, "details" : [ { "ProductName" : "Product-1" }, { "ProductName" : "Product-2" } ] }
Advertisements