mongo 中的稀疏索引和空值 [英] sparse indexes and null values in mongo

查看:42
本文介绍了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,它仍然会被索引.因此,如果该字段的缺失及其与 null 的相等性对于您的应用程序来说看起来相同,并且您希望保持 fbId 的唯一性,那么在您拥有该字段之前不要插入它它的价值.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆