我有一部分简单的代码,由于唯一的索引约束而不得不失败.但是,尽管有唯一的索引,但这两个对象都已添加到数据库中并可以查询.
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);两个对象都被保存并获得不同的_id.
Both objects are saved and get different _id.
更新. 我发现了,怎么了.保存到数据库后,这两个对象都有自己的ID,但实际上第二个对象没有保存(即使输入给定的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).
感谢araqnid,它给出了正确的答案.不幸的是,我没有足够的评分来投票.
Thanks to araqnid, that gave right answer. Unfortunately, I don't have enough rating to vote.
推荐答案在新的会话中查找时,两个对象都同时显示吗?如果保存不安全,则即使服务器实际上拒绝了第二个保存,也可能返回上面代码中分配的ID.
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.
更多推荐
MongoDB唯一索引不起作用
发布评论