Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /

ドキュメントの置換

このガイドでは、 Rustドライバーを使用して replace_one() メソッドを使用してMongoDBコレクション内のドキュメントを置き換える方法を説明します。

置き換え操作により、_idフィールドを除くドキュメントのすべての既存のフィールドが削除され、削除されたフィールドは新しいフィールドと値に置き換えられます。

注意

ドキュメント内の特定のフィールドを更新する方法については、「 ドキュメントの更新ガイド 」を参照してください。

このガイドには、次のセクションが含まれています。

  • 「ドキュメントの置き換え」では、ドライバーを使用して置換操作を実行する方法について説明します。

  • 「置換動作の変更」では、replace_one() メソッドのデフォルトの動作を変更する方法について説明します。

  • 追加情報では、このガイドで言及されている型とメソッドのリソースとAPIドキュメントへのリンクを提供します

MongoDBコレクション内の各ドキュメントには、一意かつ不変の _idフィールドがあります。置換操作を使用して _idフィールドを変更しようとすると、ドライバーは WriteError を発生させ、更新を実行しません。

replace_one() メソッドを使用して置換操作を実行できます。このメソッドは、_idフィールドを除くドキュメントの既存のフィールドをすべて削除し、削除されたフィールドを指定した新しいフィールドと値に置き換えます。

オプション ビルダのメソッドをreplace_one() メソッドに連鎖させることもできます。このメソッドの動作の変更の詳細については、このガイドの「 置換動作の変更 」セクションを参照してください。

Tip

複合操作を使用すると、1 回のアクションでデータを検索して変更できます。 詳細については、複合演算子 に関するガイドを参照してください。

replace_one() メソッドは次のパラメータを取ります。

  • 置き換えるドキュメントに一致するクエリフィルター

  • 既存のドキュメントを置き換えるフィールドと値を含む 置換ドキュメント

置き換えドキュメントは次の形式を使用します 。

doc! { "<field>": <value>, "<field>": <value>, ... }

操作が成功した場合、 replace_one()メソッドはUpdateResultタイプを返します。 UpdateResult型には、操作を説明する次のプロパティが含まれています。

プロパティ
説明

matched_count

フィルターに一致するドキュメントの数

modified_count

操作によって変更されたドキュメントの数

upserted_id

アップサートされたドキュメントの_id 、または空のドキュメントがない場合は空

replace_one()に渡したクエリフィルターに一致するドキュメントが複数ある場合、メソッドは最初に一致したドキュメントを選択して置き換えます。 クエリフィルターに一致するドキュメントがない場合、置換操作では変更は行われません。

このセクションでは、replace_one() メソッドを使用してコレクション内のドキュメントを置き換える方法を示す例えを示します。

次のドキュメントでは、会社の従業員について説明しています。

{
"_id": ObjectId('4501'),
"name": "Matt DeGuy",
"role": "Consultant",
"team_members": [ "Jill Gillison", "Susan Lee" ]
}

この例では、 replace_one()メソッドを使用して、前のドキュメントを次のフィールドを持つドキュメントに置き換えます。

  • "Susan Lee"name

  • "Lead Consultant"role

  • [ "Jill Gillison" ]team_members

let replace_doc = doc! {
"name": "Susan Lee",
"role": "Lead Consultant",
"team_members": vec! [ "Jill Gillison" ]
};
let res = my_coll
.replace_one(doc! { "name": "Matt DeGuy" }, replace_doc)
.await?;
println!(
"Matched documents: {}\nModified documents: {}",
res.matched_count, res.modified_count
);
Matched documents: 1
Modified documents: 1

置換されたドキュメントには、置換ドキュメントの内容と不変の_idフィールドが含まれます。

{
"_id": ObjectId('4501'),
"name": "Susan Lee",
"role": "Lead Consultant",
"team_members": [ "Jill Gillison" ]
}

この例では、 sample_restaurantsデータベースの restaurantsコレクション内のドキュメントを置き換えます。 replace_one() メソッドは、nameフィールドの値が "Landmark Coffee Shop" である最初のドキュメントを新しいドキュメントに置き換えます。

restaurantsコレクション内のドキュメントには、Document 型またはカスタムデータ型のインスタンスとしてアクセスできます。 コレクションのデータを表すデータ型を指定するには、強調表示された行に対して次のアクションを実行します。

  • コレクションドキュメントをBSONドキュメントとしてアクセスするには、<T> 型パラメータを <Document> に置き換え、<struct or doc> プレースホルダーを replace_doc に置き換えます。

  • Restaurant 構造体のインスタンスとしてコレクションドキュメントにアクセスするには、<T> 型パラメータを <Restaurant> に置き換え、<struct or doc> プレースホルダーを replace_struct に置き換えます。 Restaurant 構造体は、コードファイルの上部で定義されています。

AsynchronousSynchronous各実行時に対応するコードを表示するには、 タブまたは タブを選択します。

use std::env;
use mongodb::{ bson::doc, Client, Collection };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
#[tokio::main]
async fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri).await?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter = doc! { "name": "Landmark Coffee Shop" };
let replace_doc = doc! {
"borough": "Brooklyn",
"cuisine": "Café/Coffee/Tea",
"name": "Harvest Moon Café",
};
let replace_struct = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
// Replace <struct or doc> with the replace_struct or replace_doc variable
let res = my_coll.replace_one(filter, <struct or doc>).await?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1
use std::env;
use mongodb::{ bson::doc, sync::{ Client, Collection } };
use serde::{ Deserialize, Serialize };
#[derive(Serialize, Deserialize, Debug)]
struct Restaurant {
borough: String,
cuisine: String,
name: String,
}
fn main() -> mongodb::error::Result<()> {
let uri = "<connection string>";
let client = Client::with_uri_str(uri)?;
// Replace <T> with the <Document> or <Restaurant> type parameter
let my_coll: Collection<T> = client
.database("sample_restaurants")
.collection("restaurants");
let filter = doc! { "name": "Landmark Coffee Shop" };
let replace_doc = doc! {
"borough": "Brooklyn",
"cuisine": "Café/Coffee/Tea",
"name": "Harvest Moon Café",
};
let replace_struct = Restaurant {
borough: "Brooklyn".to_string(),
cuisine: "Café/Coffee/Tea".to_string(),
name: "Harvest Moon Café".to_string(),
};
// Replace <struct or doc> with the replace_struct or replace_doc variable
let res = my_coll.replace_one(filter, <struct or doc>).run()?;
println!("Replaced documents: {}", res.modified_count);
Ok(())
}
Replaced documents: 1

ReplaceOptions 構造体フィールドを設定するオプション メソッドを呼び出すことで、replace_one() メソッドの動作を変更できます。

注意

設定オプション

オプション ビルダのメソッドをreplace_one()メソッド呼び出しに直接連鎖させることで、 ReplaceOptionsフィールドを設定できます。 以前のバージョンのドライバーを使用している場合は、オプション ビルダー メソッドをbuilder()メソッドに連結してReplaceOptionsインスタンスを構築する必要があります。 次に、オプション インスタンスをパラメーターとしてreplace_one()に渡します。

次の表では、 ReplaceOptionsで利用できるオプションについて説明しています。

オプション
説明

array_filters

The set of filters specifying the array elements to which the update applies.

Type: Vec<Document>

bypass_document_validation

If true, allows the driver to perform a write that violates document-level validation. To learn more about validation, see the guide on Schema Validation.

Type: bool
Default: false

upsert

If true, the operation inserts a document if no documents match the query filter.

Type: bool

collation

The collation to use when sorting results. To learn more about collations, see the Collations guide.

Type: Collation
Default: None

hint

The index to use for the operation.

Type: Hint
Default: None

write_concern

The write concern for the operation. If you don't set this option, the operation inherits the write concern set for the collection. To learn more about write concerns, see Write Concern in the MongoDB Server manual.

Type: WriteConcern

let_vars

A map of parameters and values. These parameters can be accessed as variables in aggregation expressions. This option is available only when connecting to MongoDB Server versions 5.0 and later.

Type: Document

comment

An arbitrary Bson value tied to the operation to trace it through the database profiler, currentOp, and logs. This option is available only when connecting to MongoDB Server versions 4.4 and later.

Type: Bson
Default: None

次のコードは、 upsert()メソッドをreplace_one()メソッドに連結してupsertフィールドを設定する方法を示しています。

let res = my_coll
.replace_one(filter_doc, replace_doc)
.upsert(true)
.await?;

このガイドの概念の詳細については、次のドキュメントを参照してください。

このガイドで言及されているメソッドとタイプの詳細については、次のAPIドキュメントを参照してください。

戻る

Update Documents

項目一覧