Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mongodb aggregation and sorting on nested array

Below is my mongo db document structure

{
"product_json": {
"productId": 1,
"productData": [
  {
    "productName": "A",
    "productDetails": [
      {
        "manufacturedDate": "2014-08-09",
        "name": "A1",
        "size": 300
      },
      {
        "manufacturedDate": "2012-08-09",
        "name": "A2",
        "size": 200
      }
    ]
  },
  {
    "productName": "B",
    "productDetails": [
      {
        "manufacturedDate": "2015-08-09",
        "name": "B1",
        "size": 300
      },
      {
        "manufacturedDate": "2017-08-09",
        "name": "B2",
        "size": 200
       }
     ]
   }
 ]
}
}

I need to group by on "manufacturedDate" and apply sorting.Also i dont want the whole document as match.only the matched object(matched productDetails object).

like image 602
sachin Avatar asked May 07 '26 23:05

sachin


1 Answers

try this query :

db.collection.aggregate(
   [
    {$sort:  {'product_json.productData.productDetails.manufacturedDate': 1}}, 
    { $group:{
      "_id": "$product_json.productData.productDetails.manufacturedDate"
            }
    }
   ]
);
like image 78
Saurabh Mistry Avatar answered May 10 '26 19:05

Saurabh Mistry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!