如何在MongoDB集合中的嵌入式数组中添加唯一索引
问题描述:
我正试图在下面提到的mongo集合中的scorecardList.filename字段上创建唯一索引。目的是我们不应该能够在具有相同文件名的scorecardList中创建另一个元素。如何在MongoDB集合中的嵌入式数组中添加唯一索引
蒙戈架构:
{
"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]
蒙戈命令我试图如下使用在创建唯一索引是:
db.testing.createIndex(
{ "scorecardList.filename": 1 },
{
unique: true,
partialFilterExpression: {
"scorecardList.filename": { $exists: true }
}
}
);
即使索引已创建我我能够添加一个记分卡与现有的文件名。
请帮忙。
答
当谈到阵列
据我所知,唯一索引只有在不同的文档强制唯一性,你不能强制完整的唯一性,所以这将抛出一个重复键错误:
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 } ] })
我不知道是否有任何方式强制执行,你需要在蒙戈水平的限制,也许它的东西,你可以检查在应用程序逻辑中插入更新时?
alternatively, using the $addToSet function would check if the value already exists before adding it.
您的示例文档显示scorecardList.fileName,大写'N'。而你的索引正在用小写'n'在文件名上创建它。 – dyouberg