Docs 菜单

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

替换文档

您可以在MongoCollection对象上使用 replaceOne()方法来替换单个文档。 此方法会删除文档中的所有现有字段和值( _id字段除外),并将其替换为替换文档。

replaceOne()方法接受与要替换的文档匹配的查询筛选器,以及包含要保存以代替匹配文档的数据的替换文档。 replaceOne()方法仅替换与过滤器匹配的第一个文档。

您可以选择将ReplaceOptions的实例传递给replaceOne()方法,以指定该方法的行为。 例如,如果将ReplaceOptions对象的upsert字段设置为true ,则如果没有文档与查询筛选器匹配,操作则会插入替换文档中字段的新文档。 有关更多信息,请参阅本页底部的ReplaceOptions API 文档链接。

成功执行后, replaceOne()方法将返回UpdateResult的实例。 您可以通过调用getModifiedCount()方法来检索已修改文档数量等信息。 如果您在实例中设置了_id getUpsertedId()upsert(true)ReplaceOptions,并且操作导致插入了新文档,则还可以通过调用 方法检索文档的字段的值。

如果替换操作失败,驱动程序会引发异常。 例如,如果您尝试在替换文档中为不可变字段_id指定与原始文档不同的值,则该方法会抛出MongoWriteException ,其中包含以下消息:

After applying the update, the (immutable) field '_id' was found to have been altered to _id: ObjectId('...)

如果替换文档包含违反唯一索引规则的更改,该方法会引发MongoWriteException错误,并显示类似于以下内容的错误消息:

E11000 duplicate key error collection: ...

有关特定条件下引发的异常类型的更多信息,请参阅本页底部链接的replaceOne()的 API 文档。

在此示例中,我们将sample_mflix数据库的movies集合中查询筛选器的第一个匹配项替换为替换文档。 除_id字段之外的所有字段都将从原始文档中删除,并替换为替换文档。

replaceOne()操作运行之前,原始文档包含多个描述电影的字段。操作运行后,生成的文档仅包含替换文档指定的字段( titlefullplot )以及_id字段。

以下代码段使用以下对象和方法:

  • 传递给 replaceOne() 方法的查询筛选器eq 筛选器仅会匹配标题与 'Music of the Heart' 文本完全匹配的电影。

  • 替换文档,其中包含用于替换匹配文档(如果存在)的文档。

  • upsert选项设置为trueReplaceOptions对象。 此选项指定,如果查询筛选器与任何文档都不匹配,则该方法应插入替换文档中包含的数据。

注意

该示例使用连接 URI 连接到 MongoDB 实例。如需了解有关连接到 MongoDB 实例的更多信息,请参阅连接指南

// Replaces the first document that matches a filter by using the Java driver
package usage.examples;
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: 1
Upserted id: null

或者,如果示例导致更新或插入:

Modified document count: 0
Upserted id: BsonObjectId{value=...}

如果查询被替换的文档,输出将类似于以下内容:

Document {
{ _id=...,
title=50 Violins,
fullplot=A dramatization of the true story of Roberta Guaspari who co-founded the Opus 118 Harlem School of Music
}
}

提示

旧版 API

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

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

  • replaceOne

  • ReplaceOptions

  • UpdateResult

  • eq()

← 更新多个文档