gpt4 book ai didi

mongodb - mongodb 是否能够索引空值?

转载 作者:可可西里 更新时间:2023-11-01 10:25:37 24 4
gpt4 key购买 nike

我有一个帖子,我想将其字段 postStatus 设置为 true false 或 null。我想知道 mongo 是否能够索引空值。

此外,如果我选择执行 null、true 和 false 与使用 -1,0,1(或任何 3 个整数)有什么不同吗?

谢谢

最佳答案

null 的索引

是的,null 值被索引了,如果您尝试将第二个 null 值添加到唯一索引中,就可以证明这一点:

connecting to: test
> db.idxtest.createIndex({a:1},{unique:true})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.idxtest.insert({a:"foo"})
WriteResult({ "nInserted" : 1 })
> db.idxtest.insert({b:"bar"})
WriteResult({ "nInserted" : 1 })
> db.idxtest.insert({c:"baz"})
WriteResult({
"nInserted" : 0,
"writeError" : {
"code" : 11000,
"errmsg" : "E11000 duplicate key error index: test.idxtest.$a_1 dup key: { : null }"
}
})

证明 null 值很重要的另一种方法是对文档包含 null 值的索引字段进行排序:

> db.idxtest2.createIndex({a:1})
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
> db.idxtest2.insert({a:1})
WriteResult({ "nInserted" : 1 })
> db.idxtest.insert({a:2})
WriteResult({ "nInserted" : 1 })
> db.idxtest2.insert({b:2})
WriteResult({ "nInserted" : 1 })
> db.idxtest2.insert({a:null})
WriteResult({ "nInserted" : 1 })
> db.idxtest2.find().sort({a:1})
{ "_id" : ObjectId("56786a93ada44c7ffcd38f9f"), "b" : 2 }
{ "_id" : ObjectId("56786aa1ada44c7ffcd38fa0"), "a" : null }
{ "_id" : ObjectId("56786a65ada44c7ffcd38f9d"), "a" : 1 }
> db.idxtest2.find().sort({a:-1})
{ "_id" : ObjectId("56786a65ada44c7ffcd38f9d"), "a" : 1 }
{ "_id" : ObjectId("56786aa1ada44c7ffcd38fa0"), "a" : null }
{ "_id" : ObjectId("56786a93ada44c7ffcd38f9f"), "b" : 2 }

请注意,隐式 null 值具有优先权;可以说,它们是“更多”null,因为它们甚至没有相应的 key 。

关于 bool 值

根据 BSON specification , bool 值是一个字节,而整数至少是一个占用 4 个字节的 32 位整数。所以它确实有所作为,如果您有数百万个条目,那么总计... ...好吧,几兆字节。 ;) 所以对于所有实际目的来说,没有区别。

关于mongodb - mongodb 是否能够索引空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34401915/

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