我有一段简单的代码,但由于唯一性索引限制,它必须失败。然而,这两个对象都已被添加到数据库中,并且可以查询,尽管存在唯一性索引。
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,提供了正确的答案。不幸的是,我没有足够的评分来投票。