在 MongoDB 3.2 中创建索引以避免重复 documents/rows

Create index in MongoDB 3.2 to avoid duplicated documents/rows

我正在使用 MongoDB 3.2 并希望避免在我的 collection 中重复。为此,我使用 createIndex() 方法(我尝试了不同的变体,其中 none 不起作用):

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 and/or guid.content 字段上有索引,为什么 MongoDB 也会添加重复项?以及如何解决?我希望能够只添加一次具有相同 guid 字段的文档。

以下是文档结构示例:

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

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

您需要的不是常规索引,而是带有 options-object 的 an unique index. These are created by using the method createIndex(DBObject keys, DBObject options),其中 uniquetrue

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

Phillip 的帮助下,我针对 [=26= 中的“如何避免重复/插入时跳过重复”问题编写了一个完整的解决方案] 3.2 for 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());
        }
    }

请随意使用此 ready-to-use 解决方案。