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.

2
  • is there possibility of two newspaper in same array(like with different unitPrice)? and you want count of occurrence? or sum of quantity? Commented Dec 21, 2016 at 7: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} } Commented Dec 21, 2016 at 7:36

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks felix ! It solved my problem. btw, what is the use of $unwind
@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

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.