Update Documents
在此页面上
Overview
In this guide, you can learn how to update documents in a MongoDB collection. Update operations specify the fields and values to change in one or more documents. They apply changes specified in an update document to one or more documents that match your query filter.
To learn how to updated embedded arrays or to update or insert in a single operation, see the following pages:
Update operations can modify fields and values:
The updateOne() method changes the first document your query filter matches and the
updateMany() method changes all the documents your query filter matches.
您可以在MongoCollection
实例上调用updateOne()
和updateMany()
方法,如下所示:
collection.updateOne(<query>, <updateDocument>); collection.updateMany(<query>, <updateDocument>);
更新操作参数
updateOne()
和updateMany()
方法均具有以下参数:
query
指定了一个查询筛选条件,且其中包含用于匹配集合中要更新的文档的条件。update
指定了要在匹配的一个或多个文档中进行修改的字段和值。本节中的示例使用更新构建器来创建更新文档。(可选)
updateOptions
指定了您可以设置的选项,以自定义驱动程序执行更新操作的方式。要了解有关此类型的更多信息,请参阅 API 文档中的 UpdateOptions。
您可以使用Updates
构建器创建updateDocument
,如下所示:
Bson update = Updates.operator(<field>, <value>);
示例
在以下示例中,一家油漆店销售五种不同颜色的油漆。 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);
If multiple documents match the query filter specified in
the updateOne()
method, it updates the first result. You can
specify a sort in an UpdateOptions
instance to apply an order to
matched documents before the server performs the update operation, as
shown in the following code:
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 手册中的唯一索引。
Update Example: Full File
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
The following code is a complete, standalone file that performs an update one operation and an update many operation:
// 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
指定了您可以设置的选项,以自定义驱动程序执行替换操作的方式。要了解有关此类型的更多信息,请参阅 API 文档中的 ReplaceOptions。
替换一个示例
油漆存储意识到他们必须再次更新库存。 他们以为是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 }
If multiple documents match the query filter specified in
the replaceOne()
method, it replaces the first result. You can
specify a sort in a ReplaceOptions
instance to apply an order to
matched documents before the server performs the replace operation, as
shown in the following code:
ReplaceOptions options = ReplaceOptions.sort(ascending("qty")); UpdateResult result = collection.replaceOne(filter, document, options);
如果替换操作中与查询筛选器匹配的文档有零个,则replaceOne()
不会对集合中的文档进行任何更改。 请参阅我们的更新或插入指南,了解如何在没有匹配的文档时插入新文档而不是替换文档。
重要
replaceOne()
方法无法对违反集合唯一索引约束的文档进行更改。 有关唯一索引约束的更多信息,请参阅 MongoDB Server 手册中的唯一索引。
Replace One Example: Full File
注意
设置示例
此示例使用连接 URI 连接到MongoDB实例。要学习;了解有关连接到MongoDB实例的更多信息,请参阅创建 MongoClient指南。此示例还使用Atlas示例数据集包含的 movies
sample_mflix
数据库中的 集合。您可以按照Atlas入门指南,将它们加载到MongoDB Atlas免费套餐上的数据库中。
The following code is a complete, standalone file that performs a replace one operation.
// 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 文档
For more information about the methods and classes used on this page, see the following API documentation: