mongodb - Mongo 查询 : $exist NULL value

标签 mongodb mongoose

我在 Mongo 集合中有以下对象:

{ 
    "active" : true,
    "startDate": Date( 1434355148265 ), // Mon Jun 15 2015 15:59:08 GMT+0800 (HKT)
    "endDate": null,
    "lastFeedSearch": null,
    "lastTopicSearch": null
}

然后我尝试运行以下查询,但它似乎没有返回任何对象

{  
   "active":true,
   "$and":[  
        {  
         "$or":[  
            {  
               "startDate":{  
                  "$exists": false
               }
            },
            {  
               "startDate":{  
                  "$lte": "2015-06-16T07:07:30+00:00"
               }
            }
         ]
      },
      {  
         "$or":[  
            {  
               "endDate":{  
                  "$exists": false
               }
            },
            {  
               "endDate":{  
                  "$gte": "2015-06-16T07:07:30+00:00"
               }
            }
         ]
      },
      {  
         "$or":[  
            {  
               "$or":[  
                  {  
                     "lastTopicSearch":{  
                        "$lte": "2015-06-16T06:07:30+00:00"
                     }
                  },
                  {  
                     "lastTopicSearch":{  
                        "$exists": false
                     }
                  }
               ]
            },
            {  
               "$or":[  
                  {  
                     "lastFeedSearch":{  
                        "$lte": "2015-06-16T06:52:30+00:00"
                     }
                  },
                  {  
                     "lastFeedSearch":{  
                        "$exists": false
                     }
                  }
               ]
            }
         ]
      }
   ]
}

据我所知,所有这些 $or 条件至少应该匹配。 据我所知,这是因为 $exists 似乎没有考虑 null 值,尽管文档说它应该考虑。

最佳答案

来自 MongoDB official $exists docs :

When <boolean> is true, $exists matches the documents that contain the field, including documents where the field value is null. If <boolean> is false, the query returns only the documents that do not contain the field.

换句话说,$existsnull 视为有效值。因此,{"$exists": false} 仅匹配相应字段为 undefined 的文档,而不是 null

尝试将您的字段与 null 匹配:

{
    "lastTopicSearch": null
}

此查询将匹配 nullundefined 值。

关于mongodb - Mongo 查询 : $exist NULL value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30862887/

相关文章:

node.js - Mongoose 连接抛出警告

java - 使用 MongoDB、Java 和 Jongo 创建动态查询

node.js - Typescript 在 Mongoose pre hook 中抛出编译错误(预期有 1 个参数,但得到了 0)

javascript - 类型错误 Employee 不是构造函数 node.js

node.js - 使用 redis 和 mongodb 比较 ObjectId

node.js - 如何在mongoDB中分组并返回结果中的所有字段

node.js - Mongoose 查找默认值

node.js - Node JS + Mongodb : ValidationError: User validation failed: username: Path `username` is required

javascript - Node.JS 上的跟踪系统

node.js - MongoDB:如何查找与指定列表共享列表元素的文档