Docs Menu
Docs Home
/ / /
C#/.NET
/ / /

ドキュメントの変更

項目一覧

  • Overview
  • サンプル データ
  • アップデート操作
  • 必要なパラメーター
  • 1 つのドキュメントの更新
  • 多くのドキュメントの更新
  • 更新操作をカスタマイズする
  • 戻り値
  • 置換操作
  • 必要なパラメーター
  • 置換操作をカスタマイズする
  • 戻り値
  • 詳細情報
  • API ドキュメント

このガイドでは、MongoDB .NET/C# ドライバーを使用して、次の操作を実行して MongoDB コレクション内のドキュメントを変更する方法を学習できます。

  • アップデート操作

  • 置換操作

.NET/C# ドライバーは、ドキュメントを変更するための次のメソッドを提供します。それぞれに非同期バージョンと同期バージョンがあります。

  • UpdateOneAsync() or UpdateOne()

  • UpdateManyAsync() or UpdateMany()

  • ReplaceOneAsync() or ReplaceOne()

Tip

インタラクティブ ラボ

このページには、 UpdateManyAsync()メソッドを使用してデータを変更する方法を示す短いインタラクティブ ラボが含まれています。 MongoDB やコード エディターをインストールしなくても、ブラウザ ウィンドウでこのラボを直接完了できます。

ラボを開始するには、ページ上部の [ Open Interactive Tutorialボタンをクリックします。 ラボを全画面形式に展開するには、ラボ ペインの右上隅にある全画面ボタン( )をクリックします。

このガイドの例では、 sample_restaurantsデータベースのrestaurantsコレクションを使用します。 このコレクションのドキュメントでは、次のRestaurantAddressGradeEntryクラスをモデルとして使用します。

public class Restaurant
{
public ObjectId Id { get; set; }
public string Name { get; set; }
[BsonElement("restaurant_id")]
public string RestaurantId { get; set; }
public string Cuisine { get; set; }
public Address Address { get; set; }
public string Borough { get; set; }
public List<GradeEntry> Grades { get; set; }
}
public class Address
{
public string Building { get; set; }
[BsonElement("coord")]
public double[] Coordinates { get; set; }
public string Street { get; set; }
[BsonElement("zipcode")]
public string ZipCode { get; set; }
}
public class GradeEntry
{
public DateTime Date { get; set; }
public string Grade { get; set; }
public float? Score { get; set; }
}

注意

restaurants コレクションのドキュメントは、キャメル ケースの命名規則を使用します。このガイドの例では、ConventionPack を使用してコレクション内のフィールドをパスカル ケースに逆シリアル化し、Restaurant クラスのプロパティにマップします。

カスタム直列化について詳しくは、「 カスタム直列化 」を参照してください。

このコレクションは、Atlas が提供するサンプル データセットから構成されています。 MongoDB クラスターを無料で作成して、このサンプル データをロードする方法については、クイック スタートを参照してください。

MongoDB では、次の方法で更新操作を実行できます。

  • UpdateOne()は、検索条件に一致する最初のドキュメントを更新します。

  • UpdateMany()は、検索条件に一致するすべてのドキュメントを更新します

各更新方法には次のパラメーターが必要です。

  • アップデートするレコードを決定するクエリフィルタードキュメント 。 クエリフィルターの詳細については、 MongoDB サーバーのマニュアルを参照してください。

  • 更新演算子(実行する更新の種類)と変更する必要があるフィールドと値を指定する更新ドキュメント。 更新演算子とその使用方法の完全なリストについては、「フィールド更新演算子 のマニュアル ページ」を参照してください。

.NET/C# ドライバーは、クエリフィルターとアップデート ドキュメントの両方の作成を簡素化するBuildersクラスを提供します。 次のコード例では、 Buildersを使用して更新操作のパラメータとして使用する 2 つのドキュメントを作成します。

  • cuisineフィールド値が「Pizza」であるレストランを検索するクエリフィルター

  • これらのレストランのcuisineフィールドの値を「Pasta and cake」に設定するアップデート ドキュメント

const string oldValue = "Pizza";
const string newValue = "Pasta and breadsticks";
// Creates a filter for all documents with a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Cuisine, oldValue);
// Creates instructions to update the "cuisine" field of documents that
// match the filter
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Cuisine, newValue);
// Updates all documents that have a "cuisine" value of "Pizza"
return _restaurantsCollection.UpdateMany(filter, update);

Tip

更新操作における集計パイプライン

MongoDB バージョン4.2以降を使用している場合は、更新操作で 集計ステージ のサブセットで構成された集計パイプラインを使用できます。 更新操作で使用される集計パイプラインで MongoDB がサポートする集計ステージの詳細については、 集計パイプラインを使用して更新を構築するに関するチュートリアル を参照してください

次のコードは、非同期UpdateOneAsync()メソッドまたは同期UpdateOne()メソッドを使用して 1 つのドキュメントを更新する方法を示しています。

var result = await _restaurantsCollection.UpdateOneAsync(filter, update);
var result = _restaurantsCollection.UpdateOne(filter, update);

次のコードは、非同期UpdateManyAsync()メソッドまたは同期UpdateMany()メソッドを使用して、一致したドキュメントをすべてアップデートする方法を示しています。

var result = await _restaurantsCollection.UpdateManyAsync(filter, update);
var result = _restaurantsCollection.UpdateMany(filter, update);

Tip

これらのメソッドを使用する実行可能な例については、「追加情報 」を参照してください。

どちらの方法でも、アップデート操作を構成するために使用できるオプションを表す追加のパラメータとしてUpdateOptionsオブジェクトを受け入れます。 UpdateOptionsプロパティを指定しない場合、ドライバーは更新操作をカスタマイズしません。

UpdateOptionsタイプでは、次のプロパティを持つオプションを構成できます。

プロパティ
説明
ArrayFilters
Specifies which array elements to modify for an update operation on an array field. See the MongoDB server manual for more information.
BypassDocumentValidation
Specifies whether the update operation bypasses document validation. This lets you update documents that don't meet the schema validation requirements, if any exist. See the MongoDB server manual for more information on schema validation.
Collation
Specifies the kind of language collation to use when sorting results. See the MongoDB server manual for more information on collation.
Comment
Gets or sets the user-provided comment for the operation. See the MongoDB server manual for more information.
Hint
Gets or sets the index to use to scan for documents. See the MongoDB server manual for more information.
IsUpsert
Specifies whether the update operation performs an upsert operation if no documents match the query filter. See the MongoDB server manual for more information.
Let
Gets or sets the let document. See the MongoDB server manual for more information.

UpdateOne()メソッドとUpdateMany()メソッドはそれぞれUpdateResultオブジェクトを返します。 UpdateResult型には次のプロパティが含まれています。

プロパティ
説明
IsAcknowledged
Indicates whether the update operation was acknowledged by MongoDB.
IsModifiedCountAvailable
Indicates whether you can read the count of updated records on the UpdateResult.
MatchedCount
The number of documents that matched the query filter, regardless of how many were updated.
ModifiedCount
The number of documents updated by the update operation. If an updated document is identical to the original, it won't be included in this count.
UpsertedId
The ID of the document that was upserted in the database, if the driver performed an upsert.

次のコードでは、 UpdateMany()メソッドを使用して、 boroughフィールドの値が「manhattan」であるすべてのドキュメントを検索し、これらのドキュメントのborough値を「manhattan(north)」に更新します。 IsUpsertオプションがtrueに設定されているため、クエリフィルターが既存のドキュメントと一致しない場合、ドライバーは新しいドキュメントを挿入します。

var filter = Builders<Restaurant>.Filter
.Eq(restaurant => restaurant.Borough, "Manhattan");
var update = Builders<Restaurant>.Update
.Set(restaurant => restaurant.Borough, "Manhattan (north)");
UpdateOptions opts = new UpdateOptions()
{
Comment = new BsonString("Borough updated for C# Driver Fundamentals"),
IsUpsert = true
};
Console.WriteLine("Updating documents...");
var result = _restaurantsCollection.UpdateMany(filter, update, opts);
Console.WriteLine($"Updated documents: {result.ModifiedCount}");
Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}");

注意

上記の例ではUpdateMany()ではなくUpdateOne()メソッドが使用されていた場合、ドライバーは一致したドキュメントの最初の 個のドキュメントのみをアップデートします。

MongoDB ではReplaceOne()メソッドを使用して置換操作を実行できます。 このメソッドは、検索条件に一致する最初のドキュメントからすべてのフィールド( _idフィールドを除く)を削除し、指定したフィールドと値をドキュメントに挿入します。

ReplaceOne() メソッドには次のパラメーターが必要です。

  • 置き換えるレコードを決定する クエリフィルター ドキュメント 。

  • 置換ドキュメントで、新しいドキュメントに挿入するフィールドと値を指定します。 コレクション内のドキュメントが C# クラスにマッピングされている場合、置換ドキュメントはこのクラスのインスタンスにすることができます。

アップデート操作と同様に、.NET/C# ドライバーのBuildersクラスを使用してクエリフィルターを作成できます。 次のコード例では、 Buildersを使用して、 nameフィールド値が「Pizzaクライアント」のレストランを検索するクエリフィルターを作成します。 このコードでは、最初に一致したドキュメントを置き換える新しいRestaurantオブジェクトも作成されます。

// Creates a filter for all restaurant documents that have a "cuisine" value of "Pizza"
var filter = Builders<Restaurant>.Filter
.Eq(r => r.Cuisine, "Pizza");
// Finds the ID of the first restaurant document that matches the filter
var oldPizzaRestaurant = _restaurantsCollection.Find(filter).First();
var oldId = oldPizzaRestaurant.Id;
// Generates a new restaurant document
Restaurant newPizzaRestaurant = new()
{
Id = oldId,
Name = "Mongo's Pizza",
Cuisine = "Pizza",
Address = new()
{
Street = "Pizza St",
ZipCode = "10003"
},
Borough = "Manhattan",
};
// Replaces the existing restaurant document with the new document
return _restaurantsCollection.ReplaceOne(filter, newPizzaRestaurant);

重要

_idフィールドの値は不変です。 置き換えドキュメントで_idフィールドに値が指定される場合は、既存のドキュメントの_id値と一致する必要があります。

次のコードは、非同期ReplaceOneAsync()メソッドまたは同期ReplaceOne()メソッドを使用して 1 つのドキュメントを置き換える方法を示しています。

var result = await _restaurantsCollection.ReplaceOneAsync(filter, newRestaurant);
var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant);

Tip

これらのメソッドを使用する実行可能な例については、「追加情報 」を参照してください。

ReplaceOne()メソッドは、置換操作を構成するために使用できるオプションを表す追加のパラメータとしてReplaceOptionsオブジェクトをオプションで受け入れます。 ReplaceOptionsプロパティを指定しない場合、ドライバーは置換操作をカスタマイズしません。

ReplaceOptionsタイプでは、次のプロパティを持つオプションを構成できます。

プロパティ
説明
BypassDocumentValidation
Specifies whether the replace operation bypasses document validation. This lets you replace documents that don't meet the schema validation requirements, if any exist. See the MongoDB server manual for more information on schema validation.
Collation
Specifies the kind of language collation to use when sorting results. See the MongoDB server manual for more information on collation.
Comment
Gets or sets the user-provided comment for the operation. See the MongoDB server manual for more information.
Hint
Gets or sets the index to use to scan for documents. See the MongoDB server manual for more information.
IsUpsert
Specifies whether the replace operation performs an upsert operation if no documents match the query filter. See the MongoDB server manual for more information.
Let
Gets or sets the let document. See the MongoDB server manual for more information.

ReplaceOne()メソッドはReplaceOneResultオブジェクトを返します。 ReplaceOneResult型には次のプロパティが含まれています。

プロパティ
説明
IsAcknowledged
Indicates whether the replace operation was acknowledged by MongoDB.
IsModifiedCountAvailable
Indicates whether you can read the count of replaced records on the ReplaceOneResult.
MatchedCount
The number of documents that matched the query filter, regardless of whether one was replaced.
ModifiedCount
The number of documents replaced by the replace operation.
UpsertedId
The ID of the document that was upserted in the database, if the driver performed an upsert.

次のコードでは、 ReplaceOne()メソッドを使用して、 nameフィールドの値が「Pizza Down」である最初のドキュメントを検索し、このドキュメントを「 Engine World 」という名前の新しいRestaurantドキュメントに置き換えます。 IsUpsertオプションがtrueに設定されているため、クエリフィルターが既存のドキュメントと一致しない場合、ドライバーは新しいドキュメントを挿入します。

var filter = Builders<Restaurant>.Filter.Eq(restaurant => restaurant.Name, "Pizza Town");
Restaurant newRestaurant = new()
{
Name = "Food World",
Cuisine = "American",
Address = new BsonDocument
{
{"street", "Food St"},
{"zipcode", "10003"},
},
Borough = "Manhattan",
};
ReplaceOptions opts = new ReplaceOptions()
{
Comment = new BsonString("Restaurant replaced for .NET/C# Driver Fundamentals"),
IsUpsert = true
};
Console.WriteLine("Replacing document...");
var result = _restaurantsCollection.ReplaceOne(filter, newRestaurant, opts);
Console.WriteLine($"Replaced documents: {result.ModifiedCount}");
Console.WriteLine($"Result acknowledged? {result.IsAcknowledged}");

更新操作と置換操作の実行可能な例については、次の使用例を参照してください。

クエリフィルターの作成の詳細については、「クエリの指定」ガイドを参照してください。

このガイドで説明したメソッドや型の詳細については、次の API ドキュメントを参照してください。

戻る

ドキュメントの挿入