2

I have collection schema like :

{
"_id" : ObjectId("582ee289618a504e5c830e03"),
"updatedAt" : ISODate("2016-11-24T05:01:59.470Z"),
"createdAt" : ISODate("2016-11-18T11:14:17.912Z"),
"requestId" : "IER5R2H",
"pickupDetails" : {
    "_id" : ObjectId("58367447b0a1ada74ad7af7e"),
    "itemsCount" : 1,
    "pickupItems" : [
        {
            "name" : "Newspaper",
            "quantity" : 15,
            "unit" : "kg",
            "unitPrice" : 9,
            "amount" : 135,
            "_id" : ObjectId("58367447b0a1ada74ad7af7f")
        }
    ]
}}

{
"_id" : ObjectId("58fff31a618a504e5c831191"),
"updatedAt" : ISODate("2016-11-21T13:37:51.267Z"),
"createdAt" : ISODate("2016-11-19T06:37:14.857Z"),
"requestId" : "M7OZY9O",
"pickupDetails" : {
    "_id" : ObjectId("5832f8afb8ec77fa3c518f97"),
    "itemsCount" : 2,
    "pickupItems" : [
        {
            "name" : "Newspaper",
            "quantity" : 18,
            "unit" : "kg",
            "unitPrice" : 11,
            "amount" : 198,
            "_id" : ObjectId("5832f8afb8ec77fa3c518f98")
        },
        {
            "name" : "Plastic",
            "quantity" : 4,
            "unit" : "kg",
            "unitPrice" : 11,
            "amount" : 44,
            "_id" : ObjectId("584a853e46c71be3585bfb5a")
        }

    ]
}}

I need to add the quantity based on the name of pickupItems, like "Newspaper" etc. Suppose quantity of Newspaper for a particular day. As per the below data, result should be like, {"Newspaper":33}, for a particular date.

Sachin Bhandari
  • 524
  • 4
  • 19
  • is there possibility of two newspaper in same array(like with different unitPrice)? and you want count of occurrence? or sum of `quantity`? – Mohsen ZareZardeyni Dec 21 '16 at 07:18
  • No there is not a possibility of two newspaper in same array and I want sum of quantity of 'pickupItems'. like{ {"Newspaper":33},{"Plastic":4} } – Sachin Bhandari Dec 21 '16 at 07:36

1 Answers1

2

try this :

db.collection.aggregate([
   {
      $unwind:"$pickupDetails.pickupItems"
   },
   {
      $group:{
         _id:"$pickupDetails.pickupItems.name",
         quantity:{
            $sum:"$pickupDetails.pickupItems.quantity"
         }
      }
   }
])

output:

{ "_id" : "Plastic", "quantity" : 4 }
{ "_id" : "Newspaper", "quantity" : 33 }

you can add a $match stage at the begining of the pipeline to get results for a particular day

felix
  • 9,007
  • 7
  • 41
  • 62
  • Thanks felix ! It solved my problem. btw, what is the use of $unwind – Sachin Bhandari Dec 21 '16 at 07:34
  • 1
    @SachinBhandari $unwind deconstructs an array field from the input documents to output a document for each element, so you have a document for each item in the array – felix Dec 21 '16 at 07:45