【发布时间】:2020-01-17 04:16:39
【问题描述】:
我正在检查查询非值的逻辑,并注意到在使用 mongo shell 时,它区分了 undefined 和 null 值。
> 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 })
当你查询集合时,你会得到这个:
> 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 的记录。
> db.test.find({ a : null })
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
这是 MongoDB 中的错误吗? 如何正确查询空/未定义/未设置的字段?
编辑
所以我可以用这个查询未设置的值:
db.test.find({ $or : [ { a : null }, { a : { $exists : false } } ] })
但是在这个例子中,它仍然只返回一条记录:
{ "_id" : ObjectId("52d9557fc9333565e80ccb23"), "a" : null, "b" : null, "c" : 1 }
任何人都知道 MongoDB 为什么/如何区分 undefined 和 null?这是数据在 MongoDB 中输入方式的问题吗?
【问题讨论】:
-
Mongo 错误 - jira.mongodb.org/browse/SERVER-6102。即使 shell 将未定义的值显示为 null,它也是一个仍然存在但不为 null 的值(它是一个特殊的未定义值)。如果您不想在记录中定义
a,请不要包含它。 -
@JeffStorey 是的,这只是我在测试查询时偶然发现的。如果您想将此 Jira 问题作为答案,我会接受。
标签: mongodb