我有一部分简单的代码,由于唯一索引约束而不得不失败。但是这两个对象都被添加到数据库中并且可以被查询,尽管有唯一的索引。
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。
更新。 我发现,怎么了。保存到数据库后,两个对象都有自己的 id,但实际上第二个对象没有保存(即使通过给定的 id 也无法查询)。
感谢araqnid,这给出了正确的答案。不幸的是,我没有足够的评分来投票。