MongoDBでは、配列を含むドキュメントを更新するときに、arrayFiltersを使用するオプションがあります。 パラメータ。
arrayFilters パラメータを使用すると、変更する配列要素を決定するフィルタドキュメントの配列を指定できます。
更新ドキュメントでは、$[<identifier>]を使用します arrayFiltersに一致する配列要素を識別するフィルター処理された位置演算子 更新操作の条件。
構文
構文は次のようになります:
{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }
したがって、たとえば、updateMany()と一緒に使用する場合 メソッド、それは次のようになります:
db.collection.updateMany(
{ <query conditions> },
{ <update operator>: { "<array>.$[<identifier>]" : value } },
{ arrayFilters: [ { <identifier>: <condition> } ] }
) 例
playersというコレクションがあるとします。 次のドキュメントを使用:
{ "_id" : 1, "scores" : [ 1, 5, 17 ] }
{ "_id" : 2, "scores" : [ 8, 17, 18 ] }
{ "_id" : 3, "scores" : [ 15, 11, 8 ] }
arrayFiltersを使用できます 特定の量よりも高い値を持つ配列要素のみを更新するパラメータ。
例:
db.players.updateMany(
{ scores: { $gte: 10 } },
{ $set: { "scores.$[e]" : 10 } },
{ arrayFilters: [ { "e": { $gte: 10 } } ] }
) 結果:
{ "acknowledged" : true, "matchedCount" : 3, "modifiedCount" : 3 } このメッセージは、3つのドキュメントが一致して変更されたことを示しています。
現在のドキュメントは次のようになっています。
db.players.find() 結果:
{ "_id" : 1, "scores" : [ 1, 5, 10 ] }
{ "_id" : 2, "scores" : [ 8, 10, 10 ] }
{ "_id" : 3, "scores" : [ 10, 10, 8 ] } 以前は10以上だったすべての値が10になっていることがわかります。
この場合、eを使用しました <identifier>として 。 <identifier>に注意してください 小文字で始まり、英数字のみを含める必要があります。