balaji
balaji

Reputation: 794

how to get the sum of a particular element in all the objects of an array using pymongo

Below is my collection

[{'_id': ObjectId('603e9cc2784fa0d80d8672cd'),
'name': 'balaji',
'items': [{'price': 1, 'price_range': 'A'},
{'price': 6, 'price_range': 'B'},
{'price': 4, 'price_range': 'C'}]}]

So in the above collection, we can see only one record and it contains an array with name items and this array contains objects with price and price_range attributes, may I know how to get the sum of all the prices in this array please, I tried with below query and it did not work

aggregation_string = [{"$match":{"name": "balaji"

            }},{ "$group": {
 

              "_id":  None,
             "count": { "$sum": "$items.price" }
             }}]
db.sample_collection1.aggregate(aggregation_string) 

and I am getting count as 0. Can someone please help me here.

Upvotes: 1

Views: 39

Answers (1)

Mohameth
Mohameth

Reputation: 376

In your example since you don't need to group the objects you can simply project the sum this way :

db.collection.aggregate([
  {
    "$match": {
      "name": "balaji"
    }
  },
  {
    "$project": {
      "name": 1,
      "priceTotal": {
        "$sum": "$items.price"
      }
    }
  },
])

It should works from mongoDB 3.2 and I think it's the best way.

But if you absolutely need to use the $group, you have to do it this way:

db.collection.aggregate([
  {
    "$match": {
      "name": "balaji"
    }
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": {
          "$sum": "$items.price"
        }
      }
    }
  }
])

It was your $sum query that was incomplete. Or with the unwind operator to avoid doing twice the $sum :

db.collection.aggregate([
  {
    "$match": {
      "name": "balaji"
    }
  },
  {
    "$unwind": "$items",
  },
  {
    "$group": {
      "_id": null,
      "count": {
        "$sum": "$items.price"
      }
    }
  }
])

Upvotes: 1

Related Questions