执行批量操作

bulkWrite()方法对单个集合执行批量写入操作 此方法减少了从应用程序到 MongoDB 实例的网络往返次数,从而提高了应用程序的性能。由于您只有在所有操作返回后才会收到成功状态,因此我们建议您在满足用例要求的情况下使用它。

您可以在 中指定以下一项或多项写入操作 bulkWrite()

  • insertOne
  • updateOne
  • updateMany
  • deleteOne
  • deleteMany
  • replaceOne

bulkWrite()方法接受以下参数:

  • List实现对象的WriteModel:实现WriteModel对应于上述写入操作的类。例如,InsertOneModel该类包装了insertOne写操作。有关每个类的更多信息,请参阅本页底部的 API 文档链接。
  • BulkWriteOptions指定设置的可选对象,例如是否确保您的 MongoDB 实例对您的写入操作进行排序。
笔记

重试写入有关MongoDB服务器版本3.6中批量写入操作,除非它们包括一个或多个实例运行或更高版本 UpdateManyModelDeleteManyModel

提示

默认情况下,MongoDB 按照指定的顺序(即串行)一个一个地执行批量写入操作。在有序批量写入期间,如果在处理操作过程中发生错误,MongoDB 将返回而不处理列表中的剩余操作。相反,当您设置ordered为 时false,MongoDB 会在发生错误时继续处理列表中剩余的写入操作。无序操作理论上更快,因为 MongoDB 可以并行执行它们,但只有在写入不依赖于顺序时才应该使用它们。

bulkWrite()方法返回一个BulkWriteResult对象,对象包含有关写入操作结果的信息,包括插入、修改和删除的文档数。

如果您的一个或多个操作尝试设置违反集合上唯一索引的值,则会引发异常,该异常应如下所示:

The bulk write operation failed due to an error: Bulk write operation error on server <hostname>. Write errors: [BulkWriteError{index=0, code=11000, message='E11000 duplicate key error collection: ... }].

 

同样,如果您尝试对使用架构验证的集合执行批量写入,并且您的一个或多个写入操作提供了意外的格式,您可能会遇到异常。

以下代码示例moviessample_mflix数据库中集合执行有序的批量写入操作 该示例调用bulkWrite()包括的实施例中InsertOneModel, UpdateOneModelDeleteOneModel

笔记

此示例使用连接字符串连接到 MongoDB 实例。要了解有关连接到 MongoDB 实例的更多信息,请参阅 连接指南

 

package usage.examples;
import java.util.Arrays; import org.bson.Document; import com.mongodb.MongoException; import com.mongodb.bulk.BulkWriteResult; import com.mongodb.client.MongoClient; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.DeleteOneModel; import com.mongodb.client.model.InsertOneModel; import com.mongodb.client.model.ReplaceOneModel; import com.mongodb.client.model.UpdateOneModel; import com.mongodb.client.model.UpdateOptions;
public class BulkWrite { public static void main(String[] args) { // Replace the uri string with your MongoDB deployment's connection string String uri = "<connection string uri>"; try (MongoClient mongoClient = MongoClients.create(uri)) { MongoDatabase database = mongoClient.getDatabase("sample_mflix"); MongoCollection<Document> collection = database.getCollection("movies"); try { BulkWriteResult result = collection.bulkWrite( Arrays.asList( new InsertOneModel<>(new Document("name", "A Sample Movie")), new InsertOneModel<>(new Document("name", "Another Sample Movie")), new InsertOneModel<>(new Document("name", "Yet Another Sample Movie")), new UpdateOneModel<>(new Document("name", "A Sample Movie"), new Document("$set", new Document("name", "An Old Sample Movie")), new UpdateOptions().upsert(true)), new DeleteOneModel<>(new Document("name", "Yet Another Sample Movie")), new ReplaceOneModel<>(new Document("name", "Yet Another Sample Movie"), new Document("name", "The Other Sample Movie").append("runtime", "42")) )); System.out.println("Result statistics:" + "\ninserted: " + result.getInsertedCount() + "\nupdated: " + result.getModifiedCount() + "\ndeleted: " + result.getDeletedCount()); } catch (MongoException me) { System.err.println("The bulk write operation failed due to an error: " + me); } } } }

 

输出应如下所示:

Result statistics:
inserted: 3
updated: 2
deleted: 1

 

提示
传统 API

如果您使用的是旧 API, 请参阅我们的常见问题解答页面 以了解您需要对此代码示例进行哪些更改。

 

官方文档:https://docs.mongodb.com/drivers/java/sync/current/usage-examples/bulkWrite/