gpt4 book ai didi

MongoDB 区分 undefined 与 null

转载 作者:IT老高 更新时间:2023-10-28 13:21:54 27 4
gpt4 key购买 nike

我正在检查查询非值的逻辑,并注意到在使用 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 中输入方式的问题吗?

最佳答案

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

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

关于MongoDB 区分 undefined 与 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21190651/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com