3

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).

3
  • Try this db.collection.aggregate([ { $unwind: "$product_json.productData" }, { $unwind: "$product_json.productData.productDetails" }, { $group: { _id: "$product_json.productData.productDetails.manufacturedDate", data: { $push: "$product_json.productData.productDetails" } } } ]) Commented Sep 5, 2018 at 11:22
  • @AnthonyWinzlet i have tried it..i need only the matched inner document not the entire document.. Matched document should be like below document data :[{ "manufacturedDate": "2014-08-09", "name": "A1", "size": 300 }] Commented Sep 6, 2018 at 6:36
  • use $match stage after $unwind Commented Sep 6, 2018 at 7:09

1 Answer 1

2

try this query :

db.collection.aggregate(
   [
    {$sort:  {'product_json.productData.productDetails.manufacturedDate': 1}}, 
    { $group:{
      "_id": "$product_json.productData.productDetails.manufacturedDate"
            }
    }
   ]
);
Sign up to request clarification or add additional context in comments.

7 Comments

"productData" is inside the "product_json"
query is working but i need only the matched object not entire document
@sachin , please tell me , by which field do you want to match
"productName" and "size"
@sachin , are you using node js ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.