我有以下聚合查询:

{"$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}},
}}

有没有办法从这个查询中计算这个提升计数?

最佳答案

解决这个问题的方法是:

{"$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 ] }}
}}

关于mongodb - MongoDB Aggregate - $ sum参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20498071/

10-09 12:45