具有空值的 MongoDB 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9312067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MongoDB queries with null value
提问by Dewfy
My collection (MongoDB v 2.0.2) has following records:
我的收藏(MongoDB v 2.0.2)有以下记录:
db.organization.find({})
{ "_id" : 1001, "path" : [ ], "parent" : null }
{ "_id" : 1002, "path" : [ 1001 ], "parent" : NumberLong(1001) }
organization
has indexes:
organization
有索引:
db.organization.ensureIndex({"path":1});
db.organization.ensureIndex({"parent":1},{sparse:false});
(note I put awarnes sparse : false
- to grant that null is indexed)
But, executing:
(注意我把 awarnes sparse : false
- 授予 null 被索引)但是,执行:
db.organization.find({"parent":null})
Returns empty set. What is wrong? Thank you in advance
返回空集。怎么了?先感谢您
回答by Daniel K.
I had the same issue. After reading the following documents
我遇到过同样的问题。阅读以下文件后
I tried to query for the different BSON element types and found that my null was represented as a BSON element type 6 (undefined, deprecated) instead of the expected BSON element type 10 (null).
我尝试查询不同的 BSON 元素类型,发现我的 null 表示为 BSON 元素类型 6(未定义,已弃用),而不是预期的 BSON 元素类型 10(空值)。
db.collection.find({ field: { "$type" : 6} };
回答by Andrew Orsich
Just checked following script at 2.0 and 2.0.2:
刚刚在 2.0 和 2.0.2 中检查了以下脚本:
db.items.insert({ "_id" : 1001, "path" : [ ], "parent" : null })
db.items.insert({ "_id" : 1002, "path" : [ 1001 ], "parent" : NumberLong(1001) })
db.items.ensureIndex({"path":1});
db.items.ensureIndex({"parent":1},{sparse:false});
db.items.find({"parent":null})
actually returns one document that you expect:
实际上返回您期望的一个文档:
{ "_id" : 1001,
"path" : [],
"parent" : null }
Also you can look into this doc about querying and nulls, probably should help you avoid possible future mistakes.
您也可以查看有关querying 和 nulls 的文档,可能会帮助您避免将来可能出现的错误。