无法使用稀疏mongodb创建唯一索引

无法使用稀疏mongodb创建唯一索引,mongodb,Mongodb,我正在使用mongodb 2.6.1。但是,我无法使用稀疏创建唯一索引。目前,我有以下索引: > db.products.getIndexes() [ { "v" : 1, "key" : { "_id" : 1 }, "name" : "_id_", "ns" : "snapyshop_production.products" }, { "v"

我正在使用mongodb 2.6.1。但是,我无法使用稀疏创建唯一索引。目前,我有以下索引:

> db.products.getIndexes()
[
    {
        "v" : 1,
        "key" : {
            "_id" : 1
        },
        "name" : "_id_",
        "ns" : "snapyshop_production.products"
    },
    {
        "v" : 1,
        "key" : {
            "pickup_location" : "2dsphere"
        },
        "name" : "pickup_location_2dsphere",
        "background" : true,
        "ns" : "snapyshop_production.products",
        "2dsphereIndexVersion" : 2
    },
    {
        "v" : 1,
        "key" : {
            "category_id" : 1
        },
        "name" : "category_id_1",
        "background" : true,
        "ns" : "snapyshop_production.products"
    },
    {
        "v" : 1,
        "key" : {
            "_keywords" : 1
        },
        "name" : "_keywords_1",
        "background" : true,
        "ns" : "snapyshop_production.products"
    }
]
但当我运行此命令时,它会输出错误:

> db.products.ensureIndex( { source_url: 1 }, { background: true, sparse: true, unique: true } )
{
    "createdCollectionAutomatically" : false,
    "numIndexesBefore" : 4,
    "ok" : 0,
    "errmsg" : "E11000 duplicate key error index: snapyshop_production.products.$source_url_1  dup key: { : null }",
    "code" : 11000
}

我真的不知道如何修复它。

您正在创建的稀疏索引将允许在没有
源url
字段的情况下存在多个文档,但仍然只允许存在一个字段值为
null
的文档。换句话说,稀疏索引不处理
null
值的情况,只处理缺少字段的情况

因此,处理问题的典型方法是在创建索引之前更新集合,从现有文档中删除
source\u url
字段,该字段的值为
null

db.products.update({source\u url:null},{$unset:{source\u url:true}},{multi:true})
然后在程序逻辑中将缺少字段用作
null
指示器