Docs 菜单

Docs 主页开发应用程序MongoDB 驱动程序Java (Sync) 驱动程序

更新文档

可以在 MongoCollection 对象上使用 updateOne() 方法来更新单个文档。该方法接受与要更新的文档匹配的筛选器,以及指示驱动程序如何更改匹配文档的更新语句。updateOne() 方法只更新与筛选器匹配的第一个文档。

要使用 updateOne() 方法执行更新,必须传递查询筛选器和更新文档。查询筛选器指定了对哪个文档执行更新的标准,而更新文档则提供了对其进行更改的说明。

您可以选择向 updateOne() 方法传递 UpdateOptions 的实例,以指定该方法的行为。例如,如果将 UpdateOptions 对象的 upsert 字段设置为 true,那么如果没有与查询过滤器匹配的文档,操作就会从查询和更新文档中的字段插入新文档。有关更多信息,请参阅本页底部的 UpdateOptions API 文档链接。

执行成功后,updateOne() 方法会返回一个 UpdateResult 实例。您可以调用 getModifiedCount() 方法来检索经过修改的文档数等信息,或者调用 getUpsertedId() 方法(如果您在 UpdateOptions 实例中指定了 upsert(true))来检索 _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

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

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

我们使用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

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

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

  • updateOne

  • UpdateOptions

  • combine()

  • set()

  • addToSet()

  • currentTimestamp()

  • UpdateResult

← 更新和替换操作