MongoDB unique index does not work

我怕爱的太早我们不能终老 提交于 2019-12-07 14:39:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!