MongoDBでは、$unsetを使用できます ドキュメントからフィールドを完全に削除するためのフィールド更新演算子。
$unset 演算子は、ドキュメントからフィールドとその値を削除するように特別に設計されています。
例
dogsというコレクションがあるとします。 次のドキュメントを使用:
{ "_id" : 1, "name" : "Wag", "type" : "Dog", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "type" : "Dog", "weight" : 10 }
{ "_id" : 6, "name" : "Fetch", "type" : "Dog", "weight" : 17 }
{ "_id" : 7, "name" : "Jake", "type" : "Dog", "weight" : 30 }
そして、typeを削除したいとします。 すべてのドキュメントのフィールド(およびそれぞれの値)。
これを行うことができます:
db.dogs.updateMany(
{ },
{ $unset: { type: "" } }
) 出力:
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 } これは、4つのドキュメントが一致し(最初の引数として空のクエリドキュメントを使用したため)、4つが更新されたことを示しています。
それでは、コレクションをもう一度確認しましょう:
db.dogs.find() 結果:
{ "_id" : 1, "name" : "Wag", "weight" : 20 }
{ "_id" : 2, "name" : "Bark", "weight" : 10 }
{ "_id" : 6, "name" : "Fetch", "weight" : 17 }
{ "_id" : 7, "name" : "Jake", "weight" : 30 }
type フィールドは各ドキュメントから完全に削除されました。
$unsetで指定された値に注意してください 式(つまり「」)は操作に影響を与えません。
複数のフィールドを削除
削除する複数のフィールドをカンマで区切って指定できます。
例:
db.dogs.updateMany(
{ },
{ $unset: { name: "", weight: "" } }
) 出力:
{ "acknowledged" : true, "matchedCount" : 4, "modifiedCount" : 4 } コレクションを確認してください:
db.dogs.find() 結果:
{ "_id" : 1 }
{ "_id" : 2 }
{ "_id" : 6 }
{ "_id" : 7 }
現在は_idのみです フィールドが残っています。
埋め込みドキュメント
ドット表記を使用して、埋め込まれたドキュメントからフィールドを削除できます。
petsというコレクションがあるとします。 次のドキュメントで:
{
"_id" : 1,
"name" : "Wag",
"details" : {
"type" : "Dog",
"weight" : 20,
"awards" : {
"Florida Dog Awards" : "Top Dog",
"New York Marathon" : "Fastest Dog",
"Sumo 2020" : "Biggest Dog"
}
}
}
そして、awardsを削除したいとします。 ドキュメントのフィールド。
これを行うことができます:
db.pets.updateMany(
{ _id: 1 },
{ $unset: { "details.awards": "" } }
) 出力:
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 } それでは、ドキュメントを確認しましょう:
db.pets.findOne() 結果:
{
"_id" : 1,
"name" : "Wag",
"details" : {
"type" : "Dog",
"weight" : 20
}
}
awards フィールドとその値(それ自体は埋め込みドキュメントでした)はドキュメントから削除されました。