MongoDB Aggregate - $ sum参数

时间:2013-12-10 15:13:12

标签: mongodb pymongo

我有以下聚合查询:

{"$match": {"expired":{"$exists":False}}},
  {"$group":{
    "_id":"$retailer",
    "average_price": {"$avg":"$price"},
    "highest_price": {"$max":"$price"},
    "lowest_price": {"$min":"$price"},
    "online": {"$sum":1}
}}

我想通过计算促销产品的数量来扩展这一点。我试过这个(显然无效):

{"$match": {"expired":{"$exists":False}}},
  {"$group":{
    "_id":"$retailer",
    "average_price": {"$avg":"$price"},
    "highest_price": {"$max":"$price"},
    "lowest_price": {"$min":"$price"},
    "online": {"$sum":1},
    "promomtion": {"$sum":{"promotion":True}},
}}

有没有办法从此查询中计算此促销计数?

1 个答案:

答案 0 :(得分:2)

解决了这个问题:

{"$match": {"expired":{"$exists":False}}},
  {"$group":{
    "_id":"$retailer",
    "average_price": {"$avg":"$price"},
    "highest_price": {"$max":"$price"},
    "lowest_price": {"$min":"$price"},
    "online": {"$sum":1},
    "promotion_count": { "$sum": { "$cond": [ { "$eq": [ "$promotion", True ] }, 1,0 ] }}
}}