GroupBy使用cond选择字段

时间:2018-08-14 11:24:14

标签: mongodb mongodb-query aggregation-framework

我试图在mongoDB上创建一个groupBy,使用cond选择合适的字段,但是,mongo给了我:“字段'$ cond'必须是一个累加器对象”

$group{
 "_id" : {"dateId" : "$dateId"},
 "estimated" : { "$sum" : "$estimated_records"},
 $cond: {
   if:  {"activeSelfConsumption" : {"$exists" : true}} , (I'm also not sure if this work)
   then : {"value" : { "$sum" :"$activeSelfConsumption"}}, 
   else : {"value" : { "$sum" :"$active"}} }
}

1 个答案:

答案 0 :(得分:0)

不需要

$cond运算符。请改用$ifNull

类似

{"$group":{
 "_id" : {"dateId":"$dateId"},
 "estimated":{"$sum":"$estimated_records"},
 "value":{"$sum":{"$ifNull":['$activeSelfConsumption','$active']}}
}}