【问题标题】:Using $exists in a MongoDB expression在 MongoDB 表达式中使用 $exists
【发布时间】:2018-12-21 00:18:02
【问题描述】:

作为背景,如果我想比较两个字段,我不能使用以下语法(因为它比较的是文字字符串“$lastName”而不是 $lastName 字段的内容):

"$match": { "firstName": { $ne : "$lastName"} }

我必须使用这个:

"$match": { "$expr": { $ne : [ "$firstName", "$lastName" ] } }

如果我想测试一个字段是否存在,我必须使用第一种格式:

"$match": { "fullName": { "$exists": true } }

我认为以后一种格式表达 $exists 运算符的正确方法会引发错误:

db.docs.aggregate([
  {
    "$match": { "$expr": { "$exists": [ "$fullName", true ] } }
  }
])
assert: command failed: {
        "ok" : 0,
        "errmsg" : "Unrecognized expression '$exists'",
        "code" : 168,
        "codeName" : "InvalidPipelineOperator"
} : aggregate failed

这是否意味着至少在某些情况下无法组合这些操作?具体来说,假设我想查找 either $fullName $exists OR $firstName $ne $lastName 的文档。可以表达吗?

【问题讨论】:

标签: mongodb mongodb-query


【解决方案1】:

您需要使用$or 逻辑运算符来执行此操作。

{
   "$or": [
      {
         "$expr": {
            "$ne": [
               "$firstName",
               "$lastName"
            ]
         }
      },
      {
         "fullName": {
            "$exists": true
         }
      }
   ]
}

您上次查询失败是因为 mongod 认为 $exists 是您传递给 $expr 运算符的表达式。

【讨论】:

猜你喜欢
  • 2011-11-30
  • 1970-01-01
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多