查询一个 mongodb 字段设置为 null 的文档,但排除没有该字段的文档
Query a mongodb for documents having a field set as null but excluding the documents without the field
我目前正在试验 mongodb mongoshell。
我想要获取 tomato.consensus 值为 null 的文档。以下查询匹配 1991 个文档。
db.movieDetails.find({"tomato.consensus": null}
但是一个不良的副作用是它还会 return 没有 tomato.concensus 字段的文档和根本没有 tomato 字段的文档。
我的想法是使用 $exists 运算符。此查询 returns 362 个文档。
db.movieDetails.find({"tomato.consensus": {$exists: true})
我最初的想法是获取带有字段 tomato.consensus 的文档,然后对其进行处理以提取带有 "tomato.consensus":null 的文档。 (这不起作用):
$db.movieDetails.find({"tomato.consensus": {$exists: true}}).find({"tomato.consensus": null})
$uncaught exception: TypeError: db.movieDetails.find(...).find is not a function :
是否有语法允许执行这两个操作以消除 mongo shell 中的副作用?
您确实可以将 $exist 与 $and 结合使用来检索 "tomato.consensus" 存在且为 null 的文档:
db.movieDetails.find( { $and: [ { "tomato.consensus": null }, { "tomato.consensus": { $exists: true } } ] } )
您只需要一个 $and 运算符并定义多个过滤条件
db.movieDetails.find( { $and: [ {"tomato.consensus": { $exists: true } }, {"tomato.consensus": null } ] } )
查找有关 $and 运算符和示例的更多详细信息 here。
null
和 undefined
之间存在主要区别。 Undefined 始终为 null,但在某些情况下,null 并非未定义。
检查 undefined
可以通过某些方式完成:
1) {"tomato.consensus": { $exists: false } }
2) {"tomato.consensus": undefined }
所以为了搜索空值而不是未定义的,使用查询:
{'tomato.consensus': null, 'tomato.consensus': { $exists : true }}
我目前正在试验 mongodb mongoshell。
我想要获取 tomato.consensus 值为 null 的文档。以下查询匹配 1991 个文档。
db.movieDetails.find({"tomato.consensus": null}
但是一个不良的副作用是它还会 return 没有 tomato.concensus 字段的文档和根本没有 tomato 字段的文档。
我的想法是使用 $exists 运算符。此查询 returns 362 个文档。
db.movieDetails.find({"tomato.consensus": {$exists: true})
我最初的想法是获取带有字段 tomato.consensus 的文档,然后对其进行处理以提取带有 "tomato.consensus":null 的文档。 (这不起作用):
$db.movieDetails.find({"tomato.consensus": {$exists: true}}).find({"tomato.consensus": null})
$uncaught exception: TypeError: db.movieDetails.find(...).find is not a function :
是否有语法允许执行这两个操作以消除 mongo shell 中的副作用?
您确实可以将 $exist 与 $and 结合使用来检索 "tomato.consensus" 存在且为 null 的文档:
db.movieDetails.find( { $and: [ { "tomato.consensus": null }, { "tomato.consensus": { $exists: true } } ] } )
您只需要一个 $and 运算符并定义多个过滤条件
db.movieDetails.find( { $and: [ {"tomato.consensus": { $exists: true } }, {"tomato.consensus": null } ] } )
查找有关 $and 运算符和示例的更多详细信息 here。
null
和 undefined
之间存在主要区别。 Undefined 始终为 null,但在某些情况下,null 并非未定义。
检查 undefined
可以通过某些方式完成:
1) {"tomato.consensus": { $exists: false } }
2) {"tomato.consensus": undefined }
所以为了搜索空值而不是未定义的,使用查询:
{'tomato.consensus': null, 'tomato.consensus': { $exists : true }}