定義
$setThe
$setoperator replaces the value of a field with the specified value.
互換性
次の環境でホストされる配置には $set を使用できます。
- MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud
MongoDB Enterprise: サブスクリプションベースの自己管理型 MongoDB バージョン
MongoDB Community: ソースが利用可能で、無料で使用できる自己管理型の MongoDB のバージョン
構文
The $set operator expression has the following form:
{ $set: { <field1>: <value1>, ... } }
<field> を埋め込みドキュメントまたは配列で指定するには、ドット表記を使用します。
動作
MongoDB 5.0 以降、更新演算子では名前が文字列ベースのドキュメントフィールドを辞書順に処理します。数値名のフィールドは、数値順に処理されます。詳細については、「更新演算子の動作」を参照してください。
If the field does not exist, $set adds a new field with the specified value if the new field does not violate a type constraint. If you specify a dotted path for a non-existent field, $set creates the embedded documents as needed to fulfill the dotted path to the field.
If you specify multiple field-value pairs, $set updates or creates each field.
Starting in MongoDB 5.0, mongod no longer raises an error when you use an update operator like $set with an empty operand expression ( { } ). An empty update results in no changes and no oplog entry is created (meaning that the operation is a no-op).
$set の利点
$set 演算子には、完全なドキュメント置換と比較して次の利点があります。
ターゲット更新:
$setは指定されたフィールドのみを変更し、大規模なドキュメントを操作する際に不要な書き込みとオーバーヘッドを回避することで効率的な更新を可能にします。効率的な Oplog エントリ:
$setは、ドキュメント全体ではなく、更新されたフィールドのみをoplogに書込むことでレプリケーションを最適化します。このプロセスによりoplogエントリのサイズが縮小され、ノードは変更をより効率的に複製できます。簡素化されたロジック:
$setを使用するアプリケーションは、更新を送信する前に変更されたフィールドを計算する必要はありません。MongoDB はデルタ計算を内部的に処理することで複雑さを軽減します。
例
このページの例では、sample_mflix データセット のデータを使用しています。自己管理型 MongoDB 配置にこのデータセットをロードする方法の詳細については、「サンプル データセットのロード」を参照してください。サンプル データベースに何らかの変更を加えた場合は、今ページの例を実行するには、データベースを削除して再作成する必要がある可能性があります。
最上位フィールドの設定
The following example uses the $set operator to add the label and status fields to the matching movie document:
db.movies.updateOne( { title: "The Dark Knight" }, { $set: { label: "Award Winner", status: "classic" } } )
この操作では、次の結果を返します。
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
埋め込みドキュメントでのフィールドの設定
次の例では、一致する動画の imdb 埋め込みドキュメントの highlight フィールドをドット表記を使用して更新します。
db.movies.updateOne( { title: "The Dark Knight" }, { $set: { "imdb.highlight": "Critics' Choice" } } )
この操作では、次の結果を返します。
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
重要
前の例では、ドット表記を使用して埋め込みドキュメント imdb の highlight フィールドを更新します。代わりに次の形式では、埋め込みドキュメント全体が置き換えられ、imdb から他のすべてのフィールドが削除されます。
db.movies.updateOne( { title: "The Dark Knight" }, { $set: { imdb: { highlight: "Critics' Choice" } } } )
配列内の要素の設定
The following example uses the $set operator to update the first element (array index 0) of the genres array in the matching movie document:
db.movies.updateOne( { title: "The Dark Knight" }, { $set: { "genres.0": "Thriller" } } )
この操作では、次の結果を返します。
{ acknowledged: true, insertedId: null, matchedCount: 1, modifiedCount: 1, upsertedCount: 0 }
配列のその他の更新演算子については、「配列更新演算子」を参照してください。