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

替换文档

在本指南中,您可以学习;了解如何替换MongoDB集合中的文档。替换操作指定用于替换集合中单个文档的字段和值。

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

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

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

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

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

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

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

  • (可选) replaceOptions 指定可设立的选项,以自定义驾驶员执行替换操作的方式。 要学习;了解有关此类型的更多信息,请参阅 ReplaceOptions 的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 }

油漆店意识到他们必须再次更新库存。 他们以为是 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() 不会对集合中的文档进行任何更改。请参阅我们的 更新或插入(upsert)指南,学习;了解如何在没有匹配的文档时插入新文档,而不是替换文档。

重要

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

后退

更新插入

在此页面上

  • Overview
  • 替换一种方法
  • 替换操作参数
  • 替换一个示例