文档菜单
文档首页
/ / /
Java 同步驱动程序
/ /

替换文档

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

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

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

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

如果您的替换操作失败,驱动程序会引发异常。例如,如果您尝试在替换文档中指定与原始文档不同的不可变字段 _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()

返回

更新多个