向现有数据库添加唯一稀疏索引

Add unique sparse index to an existing database

我有一个数据库,现在我想为我现有的集合添加一个唯一的稀疏索引。问题是我从 MongoDB:

收到这个错误
{
        "createdCollectionAutomatically" : false,
        "numIndexesBefore" : 3,
        "ok" : 0,
        "errmsg" : "E11000 duplicate key error index: dbname.posts.$ref.origin_1_user_1  dup key: { : null, : ObjectId('54df4f8f93a640bd16000001') }",
        "code" : 11000
}

据我所知,sparse 索引用于可能具有空值的列,所以这就是我使用 sparse 选项的原因:

db.posts.ensureIndex({ "ref.origin": 1, "user": 1 },  {  unique: true, sparse: true })

我的 createIndex 命令有什么问题?

好吧,如果 2 元组 ('ref.origin', 'user') 不是唯一的,那么您遇到了唯一键违规。在这种情况下,元组的值为 { null, ObjectId('54df4f8f93a640bd16000001') }.

索引稀疏这一事实很重要 only if the entire set of fields is absent,即即使 { null, null } 元组也不会被忽略,但它们的唯一性得到保证。这两个字段,即 ref.originuser 都必须取消设置才能工作。