在 mongoDB 聚合中的 $match 中使用 $cond [英] Use $cond within $match in mongoDB aggregation

查看:108
本文介绍了在 mongoDB 聚合中的 $match 中使用 $cond的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在聚合的其中一个阶段中的 $match 中使用 $cond ,如下所示:

i've tried to use $cond within $match in one of the stages of an aggregation as shown below :

{ "$match" : { 
  "field1" : { 
                "$cond" : {
                   "if" : { "$eq" : [ "$id" , 1206]},
                   "then" : 0,
                   "else" : 1545001200
                }
             }, 
  "field2" : value2 }}

但是我遇到了这个错误:

But i got this error :

Error:
Assert: command failed: {
"ok" : 0,
"errmsg" : "unknown operator: $cond",
"code" : 2,
"codeName" : "BadValue"
} : aggregate failed

mongodb 版本是 3.4.4.对这个问题有什么想法吗?

The mongodb version is 3.4.4. Any idea about this issue?

推荐答案

你只需要稍微改写逻辑即可.

You just have to reword the logic a little bit.

{ $match: { $expr: {
    $or: [
        { $and: [
            { $eq: [ "$id", 1206 ] },
            { $eq: [ "$field1", 0 ] }
        ]},
        { $and: [
            { $ne: [ "$id", 1206 ] },
            { $eq: [ "$field1", 1545001200 ] }
        ]},
    ],
}}}

逻辑上,这两个语句是等价的:

Logically, the two statements are equivalent:

  • 如果id == 1206,则通过检查field1 == 0匹配文档,否则通过检查field1 == 1545001200来匹配文档/li>
  • 如果 (id == 1206 and field1 == 0) 或 (id != 1206 and field1 == 1545001200).
  • Match the document by checking field1 == 0 if id == 1206, otherwise match the document by checking field1 == 1545001200
  • Match the document if either (id == 1206 and field1 == 0) or (id != 1206 and field1 == 1545001200).

这篇关于在 mongoDB 聚合中的 $match 中使用 $cond的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆