1

我在 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") }

为什么这不起作用?

4

2 回答 2

1

您不能在唯一复合索引中使用 _id,因为 _id 默认用作 MongoDB 中的唯一键本身。而不是_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')};
于 2015-04-29T23:49:39.170 回答
0

它不起作用,因为您对 使用相同的值_id,它本身具有唯一的约束。

为什么不使用这样的东西,它可以为您节省索引:

{
   _id: {
    docid: new ObjectId(),
    date: new ISODate()
  }
}
于 2015-04-30T05:28:19.743 回答