Mongodb唯一复合索引不支持日期
我在mongodb中使用唯一的复合索引时遇到问题。代码最能说明问题(在mongo shell中): 我希望doc2可以很好地插入,因为即使其_id为1,其日期也不同,但脚本返回以下错误:Mongodb唯一复合索引不支持日期,mongodb,date,indexing,unique-constraint,compound-index,Mongodb,Date,Indexing,Unique Constraint,Compound Index,我在mongodb中使用唯一的复合索引时遇到问题。代码最能说明问题(在mongo shell中): 我希望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") } 为什么这不
E11000 duplicate key error index: db.test.$_id_ dup key: { : 1 }
当我对集合执行find()时,实际上我只看到:
{ "_id" : 1, "date" : ISODate("2015-04-27T00:00:00.000Z") }
为什么这不起作用?您不能在唯一的复合索引中使用_id,因为_id在MongoDB中默认用作唯一键本身。不要使用\u id,而是使用id:
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')};
它不起作用,因为您对
\u id
使用相同的值,该值本身具有唯一的约束
为什么不使用这样的方法,这样可以为您节省索引:
{
_id: {
docid: new ObjectId(),
date: new ISODate()
}
}
{
_id: {
docid: new ObjectId(),
date: new ISODate()
}
}