mongodb - 设置复合索引时出错

标签 mongodb

我想在我的 mongoDB 中的 fb_id 和 ts 上设置复合索引。所以,我做了:

PRIMARY> db.sessions.ensureIndex( { fb_id: 1, ts: 1 }, { unique:true } );

但是我得到了以下错误:

E11000 duplicate key error index: tracking.sessions.$fb_id_1_ts_1  dup key: { : null, : null }

所以我使用 db.sessions.getIndexes() 检查了这个集合中的索引,我得到了:

[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "ns" : "tracking.sessions",
        "name" : "_id_"
    }
]

在我看来它不像是重复的 key 。我在这里做错了什么?

最佳答案

MongoDB 告诉您有多个文档(不止一个)具有相同的 fb_idts 值,null 值。换句话说,有些文档没有fb_idts 字段。因此,它违反了整个集合的唯一约束。

作为解决方法,您应该查看 sparse指标。引用自文档:

Sparse indexes only contain entries for documents that have the indexed field. Any document that is missing the field is not indexed. The index is “sparse” because of the missing documents when values are missing.

另见:

希望对您有所帮助。

关于mongodb - 设置复合索引时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36055813/

相关文章:

Mongodb 查询 - 使用复合索引时关键顺序是否重要

python - 使用 python 创建正确的 JSON 字符串

angular - 如何获取新项目ngrx的id

arrays - MongoDB - 查询数组的最后一个元素?

mongodb - NoSQL 中的博客和博客评论关系

node.js - 平均堆栈缺失架构错误 : Schema hasn't been registered for model "User"

javascript - 如果在发布时数组中只有一个对象,则 Foreach 错误

python - Create_Index 在 python 中使用 partialFilterExpression

mongodb - 通过来自不同字段的表单上传多个文件并使用express multer存储到mongodb数据库中

mongodb - 如何将 UUID 转换为 MongoDB oid