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

Update Documents

在本指南中,您可以学习;了解如何更新MongoDB集合中的文档。更新操作指定一个或多个文档中要更改的字段和值。它们将更新文档中指定的更改应用与查询过滤匹配的一个或多个文档。

要学习;了解如何更新嵌入式数组或在单个操作中更新或插入,请参阅以下页面:

  • 更新文档中的数组

  • 在单个操作中插入或更新

更新操作可以修改字段和值:

  • updateOne() 方法会更改查询过滤匹配的第一个文档,以及

  • updateMany() 方法会更改查询过滤匹配的所有文档。

您可以在 MongoCollection实例上调用 updateOne()updateMany() 方法,如下所示:

collection.updateOne(<query>, <updateDocument>);
collection.updateMany(<query>, <updateDocument>);

updateOne()updateMany()方法均具有以下参数:

  • query 指定带有条件的查询过滤,以匹配集合中要更新的文档。

  • update 指定一个或多个匹配文档中要修改的字段和值。本节中的示例使用 Updates Builder 创建更新文档。

  • (可选) updateOptions 指定可设立用于自定义驾驶员执行更新操作方式的选项。 要学习;了解有关此类型的更多信息,请参阅 UpdateOptions 的API文档。

您可以使用Updates构建器创建updateDocument ,如下所示:

Bson update = Updates.operator(<field>, <value>);

要查看更新构建者及其用法的完整列表,请参阅API文档中的更新。

在以下示例中,一家油漆店销售五种不同颜色的油漆。 paint_inventory集合代表当前库存:

{ "_id": 1, "color": "red", "qty": 5 }
{ "_id": 2, "color": "purple", "qty": 8 }
{ "_id": 3, "color": "yellow", "qty": 0 }
{ "_id": 4, "color": "green", "qty": 6 }
{ "_id": 5, "color": "pink", "qty": 0 }

以下示例演示如何更改第一个匹配文档中 color 字段的值,其中 qty 字段的值为 0

Bson filter = Filters.eq("qty", 0);
Bson update = Updates.set("color", "dandelion");
// Updates first matching document
UpdateResult result = collection.updateOne(filter, update);

如果多个文档与 updateOne() 方法中指定的查询过滤匹配,则会更新第一个结果。您可以在 UpdateOptions实例中指定排序,以便在服务器执行更新操作之前对匹配的文档应用顺序,如以下代码所示:

UpdateOptions options = UpdateOptions.sort(ascending("color"));
UpdateResult result = collection.updateOne(filter, document, options);

油漆店收到了一批新货物,需要更新库存。 这批货物包含每种油漆颜色20罐。

要更新清单,请调用updateMany()方法并指定以下内容:

  • 匹配所有颜色的查询过滤

  • 更新包含将 qty字段递增 20 的说明的文档

Bson filter = Filters.empty();
Bson update = Updates.inc("qty", 20);
// Updates all documents and prints the number of matched and modified documents
UpdateResult result = collection.updateMany(filter, update);
System.out.println("Matched document count: " + result.getMatchedCount());
System.out.println("Modified document count: " + result.getModifiedCount());

上述代码的输出如下所示:

Matched document count: 5
Modified document count: 5

下面显示了paint_inventory集合中更新后的文档:

{ "_id": 1, "color": "red", "qty": 25 }
{ "_id": 2, "color": "purple", "qty": 28 }
{ "_id": 3, "color": "yellow", "qty": 20 }
{ "_id": 4, "color": "green", "qty": 26 }
{ "_id": 5, "color": "pink", "qty": 20 }

如果更新操作中与查询筛选器匹配的文档为零,则updateMany()不会对集合中的文档进行任何更改。 请参阅我们的更新或插入指南,了解如何在没有匹配的文档时插入新文档而不是更新文档。

重要

updateOne()updateMany() 方法无法更改违反集合上唯一索引约束的文档。有关唯一索引约束的更多信息,请参阅 MongoDB Server 手册中的唯一索引

注意

设置示例

此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 moviessample_mflix数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。

以下代码是一个完整的独立运行文件,用于执行一个更新操作和多次更新操作:

// Updates the first document that matches a query filter by using the Java driver
package org.example;
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;
import static com.mongodb.client.model.Filters.gt;
public class Update {
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");
// Instructs the driver to insert a new document if none match the query
UpdateOptions options = new UpdateOptions().upsert(true);
Document updateOneQuery = new Document().append("title", "Cool Runnings 2");
// Creates instructions to update the values of three document fields
Bson updateOneUpdates = Updates.combine(
Updates.set("runtime", 99),
Updates.addToSet("genres", "Sports"),
Updates.currentTimestamp("lastUpdated"));
// Updates the first document that has a "title" value of "Cool Runnings 2"
UpdateResult result = collection.updateOne(updateOneQuery, updateOneUpdates, options);
// Prints the number of updated documents and the upserted document ID, if an upsert was performed
System.out.println("Number of documents updated - update one: " + result.getModifiedCount());
System.out.println("Upserted document ID: " + result.getUpsertedId());
Bson updateManyQuery = gt("num_mflix_comments", 50);
// Creates instructions to update the values of two document fields
Bson updateManyUpdates = Updates.combine(
Updates.addToSet("genres", "Frequently Discussed"),
Updates.currentTimestamp("lastUpdated"));
// Updates documents that have a "num_mflix_comments" value over 50
UpdateResult result = collection.updateMany(updateManyQuery, updateManyUpdates);
// Prints the number of updated documents
System.out.println("\nNumber of documents updated - update many: " + result.getModifiedCount());
}
}
}
updateOne() modified document count: 1
Upserted ID: null
updateMany() modified document count: 242

替换操作会替换集合中的一个文档。 替换发生在查询筛选器匹配的文档和替换文档之间。

replaceOne() 方法会删除匹配文档中的所有现有字段和值(_id 字段除外),并用替换文档进行替换。

您可以在MongoCollection实例上调用replaceOne()方法,如下所示:

collection.replaceOne(<query>, <replacement>);

replaceOne() 方法具有以下参数:

  • query 指定带有条件的查询过滤,以匹配集合中要替换的文档。

  • replacement 指定新 Document对象的字段和值以替换匹配的文档。

  • (可选) replaceOptions 指定可设立的选项,以自定义驾驶员执行替换操作的方式。 要学习;了解有关此类型的更多信息,请参阅 ReplaceOptions 的API文档。

油漆店意识到他们必须再次更新库存。 他们以为是 20 罐粉红色油漆,实际上是 25 罐橙色油漆。

要更新清单,请调用replaceOne()方法并指定以下内容:

  • 查询筛选器,匹配color为“粉红色”的文档

  • 替换文档,其中color为“orange”, qty为“ 25 ”

Bson filter = Filters.eq("color", "pink");
Document document = new Document("color", "orange").append("qty", 25);
// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(filter, document);
// Prints the number of matched and modified documents
System.out.println("Matched document count: " + result.getMatchedCount());
System.out.println("Modified document count: " + result.getModifiedCount());

上述代码的输出如下所示:

Matched document count: 1
Modified document count: 1

更新后的文档如下所示:

{ "_id": 5, "color": "orange", "qty": 25 }

如果多个文档与 replaceOne() 方法中指定的查询过滤匹配,则会替换第一个结果。您可以在 ReplaceOptions实例中指定排序,以便在服务器执行替换操作之前对匹配的文档应用顺序,如以下代码所示:

ReplaceOptions options = ReplaceOptions.sort(ascending("qty"));
UpdateResult result = collection.replaceOne(filter, document, options);

如果替换操作中与查询筛选器匹配的文档有零个,则replaceOne()不会对集合中的文档进行任何更改。 请参阅我们的更新或插入指南,了解如何在没有匹配的文档时插入新文档而不是替换文档。

重要

replaceOne()方法无法对违反集合唯一索引约束的文档进行更改。 有关唯一索引约束的更多信息,请参阅 MongoDB Server 手册中的唯一索引

注意

设置示例

此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 moviessample_mflix数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。

以下代码是一个完整的独立运行文件,用于执行替换操作。

// Replaces the first document that matches a filter by using the Java driver
package org.example;
import static com.mongodb.client.model.Filters.eq;
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.ReplaceOptions;
import com.mongodb.client.result.UpdateResult;
public class ReplaceOne {
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 = eq("title", "Music of the Heart");
// Creates a new document containing "title" and "fullplot" fields
Document replaceDocument = new Document().
append("title", "50 Violins").
append("fullplot", " A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music");
// Instructs the driver to insert a new document if none match the query
ReplaceOptions opts = new ReplaceOptions().upsert(true);
// Replaces the first document that matches the filter with a new document
UpdateResult result = collection.replaceOne(query, replaceDocument, opts);
// Prints the number of modified 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 replace due to an error: " + me);
}
}
}
Modified document count: 0
Upserted id: BsonObjectId{ ... }

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

后退

从游标访问数据

在此页面上

  • Overview
  • 更新操作参数
  • 示例
  • 更新一个示例
  • 更新许多示例
  • 更新示例:完整文件
  • 替换
  • 替换操作参数
  • 替换一个示例
  • 替换一个示例:完整文件
  • 更多信息
  • API 文档
  • 服务器手册条目