MongoDB区分未定义和null [英] MongoDB Differentiates Between undefined vs. null
问题描述
我正在检查用于查询非值的逻辑,并注意到使用mongo
shell时,它会区分undefined
和null
值.
I was checking logic for querying on non-values and noticed when using the mongo
shell, it differentiates between undefined
and null
values.
> use test
> db.test.insert({ a : 1, b : null, c : undefined })
> db.test.insert({ a : null, b : undefined, c : 1 })
> db.test.insert({ a : undefined, b : 1, c : null })
查询集合时,会得到以下信息:
When you query on the collection, you get this:
> db.test.find()
{ "_id" : ObjectId("52d95575c9333565e80ccb22"), "a" : 1, "b" : null, "c" : null }
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
{ "_id" : ObjectId("52d95586c9333565e80ccb24"), "a" : null, "b" : 1, "c" : null }
但是,当您在null
上进行查询时,它仅检索显式设置为null
的记录.
When you query on null
however, it only retrieves records who was explicitly set to null
.
> db.test.find({ a : null })
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
这是MongoDB中的错误吗? 如何正确查询null/undefined/non-set字段?
Is this a bug in MongoDB? How can I properly query for null/ undefined/ non-set fields?
因此,我可以使用以下方法查询未设置的值:
So I can query for not-set values with this:
db.test.find({ $or : [ { a : null }, { a : { $exists : false } } ] })
但是在此示例中,它仍然仅返回单个记录:
But in this example though, it still only returns the single record:
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
任何人都知道MongoDB为什么/如何区分undefined
和null
?这与在MongoDB中输入数据的方式有关吗?
Anyone know why/ how MongoDB differentiates between undefined
and null
? Is this an issue with how the data was entered in MongoDB?
推荐答案
如果要返回存在字段且不为null的文档,请使用{ a : {$ne : null}}
If you want to return a document where a field exists AND is not null, use { a : {$ne : null}}
未定义和null值不同,但是外壳程序将它们都显示为null- https://jira.mongodb.org/browse/SERVER-6102
Undefined and null values are different, but the shell shows them both as null - https://jira.mongodb.org/browse/SERVER-6102
这篇关于MongoDB区分未定义和null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!