1
votes

I'm having trouble with a unique compound index in mongodb. Code speaks best so (in 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);

I expect doc2 to be inserted fine because even though its _id is 1, its date is different, but the script returns this error:

E11000 duplicate key error index: db.test.$_id_ dup key: { : 1 }

When I do a find() on the collection, I do in fact only see:

{ "_id" : 1, "date" : ISODate("2015-04-27T00:00:00.000Z") }

Why does this not work?

2

2 Answers

1
votes

You can't use _id in an unique compound index as _id is used by default as unique key itself in MongoDB. Instead of _id, use 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')};
0
votes

It does not work since you use the same value for _id, which itself has a unique constraint.

Why not use something like this, which saves you an index:

{
   _id: {
    docid: new ObjectId(),
    date: new ISODate()
  }
}