mongo中的稀疏索引和空值 [英] sparse indexes and null values in mongo
问题描述
我不确定我是否正确理解稀疏索引。
I'm not sure I understand sparse indexes correctly.
我在fbId上有一个稀疏的唯一索引
I have a sparse unique index on fbId
{
"ns" : "mydb.users",
"key" : {
"fbId" : 1
},
"name" : "fbId_1",
"unique" : true,
"sparse" : true,
"background" : false,
"v" : 0
}
我希望这会允许我插入带有null的记录作为fbId,但是会引发重复的键异常。它只允许我在完全删除fbId属性时插入。
And I was expecting that would allow me to insert records with null as the fbId, but that throws a duplicate key exception. It only allows me to insert if the fbId property is removed completely.
是不是应该处理的稀疏索引?
Isn't a sparse index supposed to deal with that?
推荐答案
稀疏索引不包含错过索引字段的文档。但是,如果字段存在且值为 null
,则仍会对其进行索引。因此,如果该字段的absense及其与 null
的相等性对于您的应用程序看起来相同,并且您希望保持 fbId $ c $的唯一性c>,只要你有一个值就不要插入它。
Sparse indexes do not contain documents that miss indexed field. However, if field exists and has value of null
, it will still be indexed. So, if absense of the field and its equality to null
look the same for your application and you want to maintain uniqueness of fbId
, just don't insert it until you have a value for it.
当你有大量的文件时,你需要稀疏的索引,但只有一小部分它们包含一些字段,您希望能够通过该字段快速查找文档。创建一个普通的索引太贵了,你只会浪费宝贵的RAM来索引你不感兴趣的文档。
You need sparse indexes when you have a large number of documents, but only a small portion of them contains some field, and you want to be able to quickly find documents by that field. Creating a normal index would be too expensive, you would just waste precious RAM on indexing documents you're not interested in.
这篇关于mongo中的稀疏索引和空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!