如何使用 Java 对 MongoDB 中的文档执行批量更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35846474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:11:01  来源:igfitidea点击:

How to perform a bulk update of documents in MongoDB with Java

javamongodbmongodb-querycrudbulkinsert

提问by Mike B.

I'm using MongoDB 3.2 and MongoDB Java Driver 3.2. I have an array of a couple of hundreds of updated documents which should be now saved/stored in MongoDB. In order to do that, I iterate over the array and call for each document in this array the updateOne()method.

我正在使用 MongoDB 3.2 和 MongoDB Java 驱动程序 3.2。我有一个包含数百个更新文档的数组,这些文档现在应该保存/存储在 MongoDB 中。为了做到这一点,我遍历数组并为该数组中的每个文档调用该updateOne()方法。

Now, I want to re-implement this logic with a bulk update. I tried to find an example of bulk update in MongoDB 3.2 with MongoDB Java Driver 3.2.

现在,我想通过批量更新重新实现这个逻辑。我试图在 MongoDB 3.2 中使用 MongoDB Java Driver 3.2 找到批量更新的示例。

I tried this code:

我试过这个代码:

MongoClient mongo = new MongoClient("localhost", 27017);
DB db = (DB) mongo.getDB("test1");
DBCollection collection = db.getCollection("collection");
BulkWriteOperation builder = collection.initializeUnorderedBulkOperation();
builder.find(new BasicDBObject("_id", 1001)).upsert()
    .replaceOne(new BasicDBObject("_id", 1001).append("author", "newName"));

builder.execute();

But it seems that this approach is based on an outdated MongoDB Java Driver, such as 2.4 and uses deprecated methods.

但似乎这种方法基于过时的 MongoDB Java Driver,例如 2.4,并使用了不推荐使用的方法。

My question:
How to perform a bulk update of documents in MongoDB 3.2 with MongoDB Java Driver 3.2?

我的问题:
如何使用 MongoDB Java Driver 3.2 对 MongoDB 3.2 中的文档执行批量更新?

采纳答案by chridam

Using the example in the manual on the new bulkWrite()API, consider the following test collection which contains the following documents:

使用新bulkWrite()API手册中的示例,考虑以下包含以下文档的测试集合:

{ "_id" : 1, "char" : "Brisbane", "class" : "monk", "lvl" : 4 },
{ "_id" : 2, "char" : "Eldon", "class" : "alchemist", "lvl" : 3 },
{ "_id" : 3, "char" : "Meldane", "class" : "ranger", "lvl" : 3 }

The following bulkWrite()performs multiple operations on the characterscollection:

以下bulkWrite()characters集合执行多项操作:



Mongo shell:

蒙戈外壳:

try {
    db.characters.bulkWrite([
        { 
            insertOne:{
                "document":{
                    "_id" : 4, "char" : "Dithras", "class" : "barbarian", "lvl" : 4
                }
            }
        },
        { 
            insertOne:{
                "document": {
                    "_id" : 5, "char" : "Taeln", "class" : "fighter", "lvl" : 3
                }
            }
        },
        { 
            updateOne: {
                "filter" : { "char" : "Eldon" },
                "update" : { $set : { "status" : "Critical Injury" } }
            }
        },
        { 
            deleteOne: { "filter" : { "char" : "Brisbane"} }
        },
        { 
            replaceOne: {
               "filter" : { "char" : "Meldane" },
               "replacement" : { "char" : "Tanys", "class" : "oracle", "lvl" : 4 }
            }
        }
    ]);
}
catch (e) {  print(e); }

which prints the output:

打印输出:

{
   "acknowledged" : true,
   "deletedCount" : 1,
   "insertedCount" : 2,
   "matchedCount" : 2,
   "upsertedCount" : 0,
   "insertedIds" : {
      "0" : 4,
      "1" : 5
   },
   "upsertedIds" : {

   }
}


The equivalent Java 3.2 implementation follows:

等效的 Java 3.2 实现如下:

MongoCollection<Document> collection = db.getCollection("characters");
List<WriteModel<Document>> writes = new ArrayList<WriteModel<Document>>();
writes.add(
    new InsertOneModel<Document>(
        new Document("_id", 4)
            .append("char", "Dithras")
            .append("class", "barbarian")
            .append("lvl", 3)
    )
);
writes.add(
    new InsertOneModel<Document>(
        new Document("_id", 5)
            .append("char", "Taeln")
            .append("class", "fighter")
            .append("lvl", 4)
    )
);
writes.add(
    new UpdateOneModel<Document>(
        new Document("char", "Eldon"), // filter
        new Document("$set", new Document("status", "Critical Injury")) // update
    )
);
writes.add(new DeleteOneModel<Document>(new Document("char", "Brisbane")));
writes.add(
    new ReplaceOneModel<Document>(
        new Document("char", "Meldane"), 
        new Document("char", "Tanys")
            .append("class", "oracle")
            .append("lvl", 4)           
    )
);

BulkWriteResult bulkWriteResult = collection.bulkWrite(writes);


For your question use the replaceOne()method and this would be implemented as

对于您的问题,请使用该replaceOne()方法,这将实现为

MongoCollection<Document> collection = db.getCollection("collection");
List<WriteModel<Document>> writes = Arrays.<WriteModel<Document>>asList(
    new ReplaceOneModel<Document>(
        new Document("_id", 1001), // filter
        new Document("author", "newName"), // update
        new UpdateOptions().upsert(true) // options
    )   
);

BulkWriteResult bulkWriteResult = collection.bulkWrite(writes);