文档菜单
文档首页
/ / /
Java 同步驱动程序
/

执行批量操作

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

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

  • 插入文档

  • 更新文档

  • 更新多个文档

  • 删除文档

  • 删除多个文档

  • 替换文档

bulkWrite() 方法接受以下参数

  • 实现 WriteModel 的对象列表:实现 WriteModel 的类对应于前面的写入操作。例如,InsertOneModel 类封装了 insertOne() 写入方法,用于插入文档。有关每个类的更多信息,请参阅页面末尾的 API 文档链接。

  • BulkWriteOptions可选 对象,用于指定设置,例如是否确保您的 MongoDB 实例按顺序执行写入操作。

注意

除非包含一个或多个 UpdateManyModelDeleteManyModel 实例,否则可重试的写入在 MongoDB 服务器版本 3.6 或更高版本中在批量写入操作中运行。

技巧

默认情况下,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: ... }].

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

以下代码示例在 sample_mflix 数据库中的 movies 集合上执行顺序批量写入操作。示例 bulkWrite() 调用包括 InsertOneModelUpdateOneModelDeleteOneModel 的示例。

注意

此示例使用连接 URI 连接到 MongoDB 实例。有关连接到您的 MongoDB 实例的更多信息,请参阅连接指南.

// Runs bulk write operations on a collection by using the Java driver
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 {
// Runs a bulk write operation for the specified insert, update, delete, and replace operations
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"))
));
// Prints the number of inserted, updated, and deleted documents
System.out.println("Result statistics:" +
"\ninserted: " + result.getInsertedCount() +
"\nupdated: " + result.getModifiedCount() +
"\ndeleted: " + result.getDeletedCount());
// Prints a message if any exceptions occur during the operations
} 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,请参阅我们的常见问题解答页面了解您需要对此代码示例进行哪些更改。

有关本页面上提到的类和方法的更多信息,请参阅以下资源

  • 唯一索引 服务器手册条目

  • 模式验证 服务器手册条目

  • bulkWrite() API 文档

  • BulkWriteOptions API 文档

  • BulkWriteResult API 文档

  • InsertOneModel API 文档

  • UpdateOneModel API 文档

  • UpdateManyModel API 文档

  • 删除单个文档模型 API 文档

  • 删除多个文档模型 API 文档

  • 替换单个文档模型 API 文档

返回

删除多个