Sort the MongoDB documents in ascending order with aggregation?

MongoDBDatabaseBig Data Analytics

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"
      }
   ]
}
raja
Published on 13-May-2020 12:36:56
Advertisements