如何使用pymongo获取数组的所有objects中特定元素的总和

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

下面是我的collection

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

所以在上面的 collection 中,我们只能看到一条记录,它包含一个包含名称项的数组,这个数组包含 objects 以及价格和 price_range 属性,可以吗?请知道如何获取此数组中所有价格的总和,我尝试了以下查询但没有成功

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

            }},{ "$group": {
 

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

我的计数为 0。有人可以帮我吗?

在您的示例中,由于您不需要对对象进行分组,因此您可以简单地以这种方式投影总和:

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

它应该从 mongoDB 3.2 开始工作,我认为这是最好的方法。

但是如果你绝对需要使用 $group,你必须这样做:

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

您的 $sum 查询不完整。 或者使用 unwind 运算符来避免 $sum 的两倍:

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