问题
I have a portion of simple code, that has to fail because of unique index constraint. But both of the objects are added to database and can be queried, in spite of unique index.
BasicDBObject typeUrlIndex = new BasicDBObject();
typeUrlIndex.put(FIELD_TYPE_URL, 1);
BasicDBObject typeUrlIndexOptions = new BasicDBObject();
typeUrlIndexOptions.put("background", true);
typeUrlIndexOptions.put("sparse", true);
typeUrlIndexOptions.put("unique", true);
typeUrlIndexOptions.put("dropDups", true);
objects.ensureIndex(typeUrlIndex, typeUrlIndexOptions);
// here I can check, that index is really created, and it is true.
List<DBObject> indexes = objects.getIndexInfo();
BasicDBObject dbo1 = new BasicDBObject(FIELD_TYPE_URL, "aaa");
objects.save(dbo1);
BasicDBObject dbo2 = new BasicDBObject(FIELD_TYPE_URL, "aaa");
objects.save(dbo2);
Both objects are saved and get different _id.
Upd. I found, what's wrong. Both objects get their own id after saving to database, but actually second object is not saved (it cannot be queried, even by given id).
Thanks to araqnid, that gave right answer. Unfortunately, I don't have enough rating to vote.
回答1:
Are both objects showing up when you look in a new session? If the saves are unsafe, they could be returning with an ID assigned in the code above, even though the server will actually reject the second one.
回答2:
You need to add the { unique: true }
option when creating the index
mongodb unique index documentation
来源:https://stackoverflow.com/questions/8805048/mongodb-unique-index-does-not-work