首页 > 解决方案 > 为什么我不能在 Mongo 管道匹配中使用 $nin、$exists 等?

问题描述

对于这个答案,我一直在寻找高低,但没有任何效果。我有一个管道查询,其匹配项如下:

$match: {
  $expr: {
    $and: [
      ....
    ]
  }
}

在 $and 中,我有各种使用 $eq、$in、$ne、$gt、$lt 等的条件。

但是尽我所能,我无法让它识别 $nin 或 $exists。我正在尝试添加一个术语来搜索不存在的键,例如:

{ $exists: [ '$key', 0 ] }

我不断得到

MongoError:无法识别的表达式'$exists'

MongoError:无法识别的表达式'$nin'

有人可以帮忙吗??

标签: node.jsmongodbaggregation-framework

解决方案


您只能aggregation$exprand the中使用运算符,$nin并且$exists是查询运算符而不是查询运算符aggregation$expr在表达式之外使用上述条件。

就像是

{ "$match": {
  "key": { "$exists": true },
  "$expr": {
    "$and": [
      {...}, {...}
    ]
  }
}}

推荐阅读