3

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

    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,这给出了正确的答案。不幸的是,我没有足够的评分来投票。

4

2 回答 2

7

当您查看新会话时,这两个对象都出现了吗?如果保存不安全,它们可能会返回上面代码中分配的 ID,即使服务器实际上会拒绝第二个。

于 2012-01-10T17:14:08.247 回答
0

{ unique: true }创建索引时需要添加选项

mongodb唯一索引文档

于 2012-01-10T16:01:07.140 回答