4

我正在尝试在下面提到的 mongo 集合中的 scorecardList.filename 字段上创建唯一索引。目的是我们不能在 scorecardList 中创建另一个具有相同文件名的元素。

蒙戈模式:

{
    "Name": "Ravikant Khond",
    "PIN" : "411057",
    "scorecardList": [
        {
            "fileName" : "ScoreCard_April_2016.pdf",
            "runDate" : ISODate("2016-05-01T00:00:00.000Z"),
            "month" : "April",
            "year" : "2016"
        },
        {
            "fileName" : "ScoreCard_May_2016.pdf",
            "runDate" : ISODate("2016-06-01T00:00:00.000Z"),
            "month" : "May",
            "year" : "2016"
        }
    ]
}

[1]

我在创建唯一索引时尝试使用的 Mongo 命令如下:

db.testing.createIndex(
    { "scorecardList.filename": 1 },
    { 
        unique: true, 
        partialFilterExpression: { 
            "scorecardList.filename": { $exists: true } 
        } 
    }
);

即使已创建索引,我也可以使用现有文件名添加记分卡。

请帮忙。

4

1 回答 1

1

当涉及到数组时,您不能强制执行完全唯一性

据我所知,唯一索引仅在不同文档之间强制执行唯一性,因此这会引发重复键错误:

db.food.insert( { id: 123, name:bread, ingredients: [ { id: 456 } ] } )
db.food.insert( { id: 123, name:bread, ingredients: [ { id: 456 } ] } )

但这是允许的:

db.food.insert( { id: 123, name:bread, ingredients: [ { id: 456 }, { id: 456 } ] } )

我不确定是否有任何方法可以在 Mongo 级别强制执行您需要的约束,也许您可​​以在插入更新时检查应用程序逻辑?

或者,使用$addToSet函数将在添加之前检查该值是否已经存在。

于 2016-12-01T19:46:26.537 回答