Docs 菜单
Docs 主页
/ / /
Java (Sync) 驱动程序
/ /

更新多个文档

您可以对 MongoCollection 对象使用 updateMany() 方法更新多份文档。该方法接受与待更新文档匹配的筛选器,以及指示驱动程序如何更改匹配文档的更新语句。updateMany() 方法更新集合中与筛选器匹配的所有文档。

要使用 updateMany() 方法执行更新,必须传递查询筛选器和更新文档。查询筛选器指定要匹配集合中的哪些文档,更新文档说明对它们进行哪些更改。

您可以选择向 updateMany() 方法传递 UpdateOptions 的实例,以修改调用行为。例如,如果将 UpdateOptions 对象的 upsert 字段设置为 true,且没有文档与指定的查询筛选器匹配,则操作会插入由查询和更新文档中的字段组成的新文档。

在成功执行后,updateMany() 方法返回一个 UpdateResult 实例。您可以调用 getModifiedCount() 方法以检索一些信息,例如,修改的文档数量。如果您在 UpdateOptions 对象中指定了 upsert(true) ,并且操作导致插入,则可以对 UpdateResult 实例调用 getUpsertedId() 方法以检索新文档的 _id 字段。

如果更新操作失败,驱动程序会引发异常,并且不会更新与筛选器匹配的任何文档。例如,如果您尝试在更新文档中为不可变字段 _id 设置值,则updateMany() 方法不会更新任何文档,并会抛出带有以下消息的 MongoWriteException

Performing an update on the path '_id' would modify the immutable field '_id'

如果更新文档包含违反唯一索引规则的更改,该方法会引发MongoWriteException错误,并显示类似于以下内容的错误消息:

E11000 duplicate key error collection: ...

有关特定条件下引发的异常类型的更多信息,请参阅本页底部链接的updateMany()的 API 文档。

在此示例中,我们更新了sample_mflix数据库的movies集合中与查询相匹配的文档。我们对匹配文档执行以下更新:

  • 仅当 genres 数组中不存在 Frequently Discussed 时,才可将其添加到该数组中

  • lastUpdated的值设置为当前时间。

我们使用Updates构建器,这是一个工厂类,其中包含用于构造更新文档的静态辅助方法。虽然可以不使用构建器而直接传递更新文档,但构建器提供了类型检查和简化的语法。有关详细信息,请阅读我们有关“构建者”部分中的更新的指南

注意

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接指南

// Updates documents that match a query filter by using the Java driver
package usage.examples;
import static com.mongodb.client.model.Filters.gt;
import org.bson.Document;
import org.bson.conversions.Bson;
import com.mongodb.MongoException;
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.Updates;
import com.mongodb.client.result.UpdateResult;
public class UpdateMany {
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");
Bson query = gt("num_mflix_comments", 50);
// Creates instructions to update the values of two document fields
Bson updates = Updates.combine(
Updates.addToSet("genres", "Frequently Discussed"),
Updates.currentTimestamp("lastUpdated"));
try {
// Updates documents that have a "num_mflix_comments" value over 50
UpdateResult result = collection.updateMany(query, updates);
// Prints the number of updated documents
System.out.println("Modified document count: " + result.getModifiedCount());
// Prints a message if any exceptions occur during the operation
} catch (MongoException me) {
System.err.println("Unable to update due to an error: " + me);
}
}
}
}

运行该示例后,您应该会看到如下所示的输出:

Modified document count: 53

如果查询更新后的一份或多份文档,它们应如下所示:

[
Document {
{ _id=...,
plot=...,
genres=[..., Frequently Discussed, ...],
...
lastUpdated=Timestamp{...}
}
},
...
]

提示

Legacy API

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

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

  • UpdateMany

  • UpdateOptions

  • combine()

  • addToSet()

  • currentTimestamp()

  • UpdateResult

后退

更新文档