MongoDB unique index does not work
Asked Answered
B

2

3

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.

Bacchus answered 10/1, 2012 at 14:41 Comment(2)
hmm, even if you can't vote, you should be able to mark the answer as accepted, which will mark the question as answered.Bonnice
Anton, you should be able to mark this as accepted by hovering below the area where you vote on an answer and clicking the check mark you see there.Geiss
B
7

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.

Bonnice answered 10/1, 2012 at 17:14 Comment(0)
G
0

You need to add the { unique: true } option when creating the index

mongodb unique index documentation

Galileo answered 10/1, 2012 at 16:1 Comment(1)
I have added this option, look at the code:typeUrlIndexOptions.put("unique", true);Bacchus

© 2022 - 2024 — McMap. All rights reserved.