Docs 菜单
Docs 主页
/ / /
java sync
/

执行批量操作

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

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

  • insertOne

  • updateOne

  • updateMany

  • deleteOne

  • deleteMany

  • replaceOne

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

  • 实施 WriteModel 的对象的 List:实施 WriteModel 的类对应上述写入操作。例如,InsertOneModel 类封装了 insertOne 写入操作。请参阅本页底部的 API 文档链接,查看有关每个类的更多信息。

  • BulkWriteOptions可选对象,指定相关设置,例如是否确保 MongoDB 实例对写入操作进行排序。

注意

可重试写入在 MongoDB Server 版本 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: ... }].

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

以下代码示例将对 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

提示

Legacy API

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

有关此页面上所提及的类和方法的更多信息,请参阅以下资源:

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

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

  • bulkWrite() API 文档

  • BulkWriteOptions API 文档

  • BulkWriteResult API 文档

  • InsertOneModel API 文档

  • UpdateOneModel API 文档

  • UpdateManyModel API 文档

  • DeleteOneModel API 文档

  • DeleteManyModel API 文档

  • ReplaceOneModel API 文档

后退

删除多个文档