Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

mongodb unique index documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top