【问题标题】:MongoDB Differentiates Between undefined vs. nullMongoDB 区分 undefined 与 null
【发布时间】:2020-01-17 04:16:39
【问题描述】:

我正在检查查询非值的逻辑,并注意到在使用 mongo shell 时,它区分了 undefinednull 值。

> 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 为什么/如何区分 undefinednull?这是数据在 MongoDB 中输入方式的问题吗?

【问题讨论】:

  • Mongo 错误 - jira.mongodb.org/browse/SERVER-6102。即使 shell 将未定义的值显示为 null,它也是一个仍然存在但不为 null 的值(它是一个特殊的未定义值)。如果您不想在记录中定义a,请不要包含它。
  • @JeffStorey 是的,这只是我在测试查询时偶然发现的。如果您想将此 Jira 问题作为答案,我会接受。

标签: mongodb


【解决方案1】:

如果要返回字段存在且不为空的文档,请使用{ a : {$ne : null}}

Undefined 和 null 值不同,但 shell 将它们都显示为 null - https://jira.mongodb.org/browse/SERVER-6102

【讨论】:

  • 我更感兴趣的是为什么在 mongo shell 中没有返回 null 值。
【解决方案2】:

如果您想知道,为什么 MongoDB 将 undefined 转换为 null 而不是仅仅忽略这些属性 - ignoreUndefined 标志可以解决这种行为。

https://mongodb.github.io/node-mongodb-native/2.1/reference/connecting/connection-settings/

【讨论】:

  • 链接已损坏。
【解决方案3】:

【讨论】:

  • $exists 还将返回字段为 null 的文档 - 我不确定 OP 是否需要。
  • $exists : true 将返回带有null 的字段,$exists : false 返回未设置该字段的条目。不会返回具有null 值的记录。
猜你喜欢
  • 2019-02-15
  • 2018-09-19
  • 2019-05-09
  • 1970-01-01
  • 2018-12-23
  • 2023-03-18
  • 2015-05-26
  • 2018-03-19
  • 2020-08-21
相关资源
最近更新 更多