我在 mongodb 中遇到了唯一复合索引的问题。代码说得最好(在 mongo shell 中):
var collection = db.getCollection('test');
collection.drop(); // start from scratch
collection.createIndex({date:1});
collection.createIndex({_id:1, date:1}, {unique: true});
var doc1 = {_id: NumberInt(1), date: new ISODate('2015-04-27 00:00:00.000Z')};
var doc2 = {_id: NumberInt(1), date: new ISODate('2015-04-28 00:00:00.000Z')};
collection.insert(doc1);
collection.insert(doc2);
我希望 doc2 可以正常插入,因为即使它的 _id 为 1,它的日期也不同,但脚本会返回此错误:
E11000 duplicate key error index: db.test.$_id_ dup key: { : 1 }
当我对集合执行 find() 时,实际上我只看到:
{ "_id" : 1, "date" : ISODate("2015-04-27T00:00:00.000Z") }
为什么这不起作用?