子文档上的猫鼬唯一索引
问题描述:
假设我有一个简单的架构:
Let's say I have a simple schema:
var testSchema = new mongoose.Schema({
map: { type: [ mongoose.Schema.Types.Mixed ], default: [] },
...possibly something else
});
现在让我们确保对 (_id
, map._id
) 是唯一的.
Now let's ensure that pairs (_id
, map._id
) are unique.
testSchema.index({ _id: 1, 'map._id': 1 }, { unique: true });
使用 db.test.getIndexes()
快速检查显示它已创建.
Quick check using db.test.getIndexes()
shows that it was created.
{
"v" : 1,
"unique" : true,
"key" : {
"_id" : 1,
"map._id" : 1
},
"name" : "_id_1_map._id_1",
"ns" : "test.test",
"background" : true,
"safe" : null
}
问题是,这个索引被忽略了,我可以轻松地创建多个具有相同 map._id
的子文档.我可以轻松地多次执行以下查询:
The problem is, this index is ignored and I can easily create multiple subdocuments with the same map._id
. I can easily execute following query multiple times:
db.maps.update({ _id: ObjectId("some valid id") }, { $push: { map: { '_id': 'asd' } } });
并最终得到以下结果:
{
"_id": ObjectId("some valid id"),
"map": [
{
"_id": "asd"
},
{
"_id": "asd"
},
{
"_id": "asd"
}
]
}
这是怎么回事?为什么我可以推送冲突的子文档?
What's going on here? Why can I push conflicting subdocuments?
答
长话短说:Mongo 不支持子文档的唯一索引,尽管它允许创建它们...
Long story short: Mongo doesn't support unique indexes for subdocuments, although it allows creating them...