更新多个文档
您可以使用以下方法更新多个文档:在 MongoCollection
对象上,有一个名为 updateMany()
的方法。此方法接受一个 filter,用于匹配要更新的文档,以及一个 update 语句,指示驱动程序如何更改匹配的文档。updateMany()
方法会更新所有匹配过滤器的集合文档。
要使用 updateMany()
方法执行更新,您必须传递一个查询过滤器和更新文档。查询过滤器指定要匹配的集合中的哪些文档,而更新文档提供了更改它们的指令。
您可以选择将 UpdateOptions
的实例传递给 updateMany()
方法,以修改调用的行为。例如,如果您将 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
集合中匹配我们的查询的文档。我们对匹配的文档执行以下更新
如果
Frequently Discussed
不存在于genres
数组中,则将其添加到数组中将
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{...} } }, ... ]
有关本页面上提到的类和方法的更多信息,请参阅以下 API 文档