Mongodb $exists 的奇怪行为

Mongodb weird behaviour of $exists

我不明白命令 $exists 的行为。

我在collection'user'中有两个简单的文档:

/* 1 */
{
    "_id" : ObjectId("59788c2f6be212c210c73233"),
    "user" : "google"
}

/* 2 */
{
    "_id" : ObjectId("597899a80915995e50528a99"),
    "user" : "werty",
    "extra" : "very important"
}

我想检索包含字段 "extra" 且值不等于 'unimportant':

的文档

查询:

db.getCollection('users').find(
{"extra":{$exists:true},"extra": {$ne:"unimportant"}}
)

returns这两个文件。

也是查询

db.getCollection('users').find(
{"extra":{$exists:false},"extra": {$ne:"unimportant"}}
)

returns这两个文件。

$exists(当在同一字段上与另一个条件一起使用时)似乎像 'OR' 一样工作。 我做错了什么?任何帮助表示赞赏。

我使用了 mongodb 3.2.6 和 3.4.9

我看过Mongo $exists query does not return correct documents 但我没有稀疏索引。

您构建查询的方式有误,与 $exists 的工作方式无关。因为您正在检查两个条件,所以您需要一个执行逻辑 AND 运算的查询来满足这两个条件。

查询的正确语法

I want to retrieve documents which contain the field "extra" and the value is not equal to 'unimportant'

应该遵循:

db.getCollection('users').find(
    {
        "extra": {
            "$exists": true,
            "$ne": "unimportant"
        }
    }
)

或使用 $and 运算符作为:

db.getCollection('users').find(
    {
        "$and": [
            { "extra": { "$exists": true } },
            { "extra": { "$ne": "unimportant" } }
        ]
    }
)

根据 MongoDB 文档 (https://docs.mongodb.com/manual/reference/operator/query/and/):

Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.

因此,为了强制执行这两个子句的 cumpliment,您应该使用 $and 运算符,如下所示:

db.getCollection('users').find({ $and : [ { "extra": { $exists : true } }, { "extra" : { $ne : "unimportant" } } ] });