MongoDB唯一索引不起作用

Ant*_*ich 3 indexing unique-index mongodb

我有一部分简单的代码,由于唯一索引约束而必须失败.但是这两个对象都被添加到数据库中,并且可以查询,尽管有独特的索引.

    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);
Run Code Online (Sandbox Code Playgroud)

两个对象都被保存并获得不同的_id.

UPD. 我发现,出了什么问题.保存到数据库后,这两个对象都会获得自己的id,但实际上第二个对象没有保存(即使是给定的id也无法查询它).

感谢araqnid,给出了正确答案.不幸的是,我没有足够的评级来投票.

ara*_*nid 7

当您在新会话中查看时,两个对象是否都会显示?如果保存不安全,它们可能会返回上面代码中指定的ID,即使服务器实际上会拒绝第二个.