在MongoDB 3.2中创建索引以避免重复的文档/行

时间:2016-01-09 23:37:29

标签: java mongodb indexing duplicates crud

我正在使用MongoDB 3.2并希望避免我的收藏中的重复项。为了做到这一点,我使用createIndex()方法(我尝试了不同的变体,但没有一个不起作用):

dbColl.createIndex(new Document("guid", 1));
dbColl.createIndex(new BasicDBObject("guid", 1));
dbColl.createIndex(new Document("guid.content", 1));
dbColl.createIndex(new BasicDBObject("guid.content", 1));

然后我尝试用:

执行数据插入
itemsArr.forEach(
     item -> dbColl.insertOne(Document.parse(item.toString()))
);

我这样做了两次并且预计MongoDB第二次不会添加任何新行,因为数据已经添加并且guid字段上有索引。但情况并非如此,即使索引值,MongoDB也会增加重复数据。

我的问题是,即使guid和/或guid.content字段上有索引,MongoDB也会添加重复项?以及如何解决它?我希望能够仅使用相同的guid字段添加文档一次。

以下是文档结构示例: Documents Schema Example

在我的数据中,guid字段是唯一的文档标识符。

2 个答案:

答案 0 :(得分:4)

常规索引允许具有相同值的多个文档。

您需要的不是常规索引,而是an unique index。这些是使用createIndex(DBObject keys, DBObject options)方法和uniquetrue的选项对象创建的。

collection.createIndex(new BasicDBObject("guid", 1), new BasicDBObject("unique", true));

答案 1 :(得分:1)

Phillip的帮助下,我为 MongoDB 3.2 中的问题«如何避免重复/跳过重复插件»编写了一个完全有效的解决方案对于 Java驱动程序3.2.0

    IndexOptions options = new IndexOptions();

    // ensure the index is unique
    options.unique(true);
    // define the index
    dbColl.createIndex(new BasicDBObject("guid", 1), options);

    // add data to DB
    for (Object item : itemsArr) {

        // if there is a duplicate, skip it and write to a console (optionally)
        try {
            dbColl.insertOne(Document.parse(item.toString()));
        } catch (com.mongodb.MongoWriteException ex) {
            //System.err.println(ex.getMessage());
        }
    }

随意使用这个随时可用的解决方案。