从字段返回$ cond的mongo DB聚集

时间:2019-03-21 16:29:48

标签: mongodb mongodb-query aggregation-framework

我试图让一个aggregation在满足两个条件的情况下返回一个字段(在文档中), 我正在$project阶段进行尝试,并尝试将其编写如下:

"conversionName" : { "$cond" : [ { "$and" : [ { "$eq" : [ "$webpage", "Product" ] }, { "$eq" : [ "$isConverted", true ] } ] }, "$conversion.name", 0 ] }

因此,如果网页是Product并且isConverted为true,则它将在此文档中显示conversion.name的值。

The current aggregation fails due to :  "The $cond accumulator is a unary operator' on server main-shard-00-00-mhxad.gcp.mongodb.net:27017. "

聚合的其他部分工作正常。

我可以用什么方式返回一个带有$cond推荐值的值?如果没有,还有什么其他方法可以满足我的需求?

1 个答案:

答案 0 :(得分:0)

在我的项目中,它可以通过以下方式完美运行:

$cond: {
  if: {
    $and: [
      { "$eq" : [ "$webpage", "Product" ] },
      { "$eq" : [ "$isConverted", true ] },
    ],
  },
  then: "$conversion.name",
  else: 0,
},

如果它不起作用(我不明白为什么不这样做),then是一个表达式,可以是其他$cond

$cond: {
  if: { "$eq" : [ "$webpage", "Product" ] },
  then: {$cond: {if: { "$eq" : [ "$isConverted", true ] }, then: "$conversion.name", else: 0},
  else: 0,
},
相关问题