更新文档
您可以使用updateOne()
方法在 MongoCollection
对象上更新单个文档。该方法接受一个 过滤器,用于匹配要更新的文档,以及一个 更新 语句,指示驱动程序如何更改匹配的文档。 updateOne()
方法仅更新与过滤器匹配的第一个文档。
要使用 updateOne()
方法执行更新,您必须传递一个查询过滤器和更新文档。查询过滤器指定要更新的文档的准则,更新文档提供对更改的说明。
您可以选择向 updateOne()
方法传递一个 UpdateOptions
实例,以指定该方法的行为。例如,如果将 UpdateOptions
对象的 upsert
字段设置为 true
,则在没有文档匹配查询过滤器时,操作将从查询和更新文档的字段中插入新文档。有关更多信息,请参阅页面底部的 UpdateOptions
API 文档链接。
成功执行后,updateOne()
方法返回一个 UpdateResult
实例。您可以通过调用 getModifiedCount()
方法来获取修改的文档数量,或者如果您在 UpdateOptions
实例中指定了 upsert(true)
,则可以通过调用 getUpsertedId()
方法获取 _id
字段的值。
如果您的更新操作失败,驱动程序将引发异常。例如,如果您尝试在更新文档中设置不可变字段 _id
的值,该方法将抛出一个带有以下消息的 MongoWriteException
。
Performing an update on the path '_id' would modify the immutable field '_id'
如果您的更新文档包含违反唯一索引规则的更改,该方法将抛出一个类似于以下消息的 MongoWriteException
。
E11000 duplicate key error collection: ...
有关特定条件下引发的异常类型的信息,请参阅页面底部的 updateOne()
API 文档链接。
示例
在这个示例中,我们更新了 sample_mflix
数据库中 movies
集合中查询的第一个匹配项。我们对匹配的文档执行以下更新:
将
runtime
的值设置为99
如果
Sports
不存在于genres
数组中,则将其添加到数组中将
lastUpdated
的值设置为当前时间。
我们使用 Updates
构建器,这是一个包含静态辅助方法的工厂类,来构建更新文档。虽然您可以通过传递更新文档而不是使用构建器,但构建器提供了类型检查和简化的语法。有关 Updates
构建器的更多信息,请参阅我们的关于 Updates 构建器的指南.
注意
此示例通过连接URI连接到MongoDB实例。有关连接到MongoDB实例的更多信息,请参阅连接指南。
// Updates the first document that matches a query filter by using the Java driver package usage.examples; 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.UpdateOptions; import com.mongodb.client.model.Updates; import com.mongodb.client.result.UpdateResult; public class UpdateOne { 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"); Document query = new Document().append("title", "Cool Runnings 2"); // Creates instructions to update the values of three document fields Bson updates = Updates.combine( Updates.set("runtime", 99), Updates.addToSet("genres", "Sports"), Updates.currentTimestamp("lastUpdated")); // Instructs the driver to insert a new document if none match the query UpdateOptions options = new UpdateOptions().upsert(true); try { // Updates the first document that has a "title" value of "Cool Runnings 2" UpdateResult result = collection.updateOne(query, updates, options); // Prints the number of updated documents and the upserted document ID, if an upsert was performed System.out.println("Modified document count: " + result.getModifiedCount()); System.out.println("Upserted id: " + result.getUpsertedId()); // 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: 1 Upserted id: null
或者如果示例导致了更新
Modified document count: 0 Upserted id: BsonObjectId{value=...}
如果您查询更新后的文档,输出将类似于以下内容
Document { { _id=..., plot=..., genres=[Adventure, Comedy, Family, Sports], runtime=99, ... lastUpdated=Timestamp{...} } }
有关本页面上提到的类和方法的其他信息,请参阅以下API文档