MongoDB 查詢以從文件中刪除子文件?
若要從文件中刪除子文件,沿用 $pull 並與 update() 結合使用。我們首先使用文件建立集合 -
> db.demo538.insertOne( ... { ... id:101, ... "details": ... { ... anotherDetails: ... [ ... { ... "Name":"Chris", ... Age:21 ... }, ... { ... "Name":"David", ... Age:23 ... }, ... { ... "Name":"Bob", ... Age:20 ... } ... ] ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e8c8f0aef4dcbee04fbbc08") }
在集合中,藉助 find() 方法顯示所有文件 -
> db.demo538.find();
這會產生以下輸出 -
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ] } }
以下是從文件中刪除子文件的查詢 -
> db.demo538.update({ id:101}, ... {$pull : { "details.anotherDetails" : {"Age":23} } } ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在集合中,藉助 find() 方法顯示所有文件 -
> db.demo538.find();
這會產生以下輸出 -
{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 } ] } }
廣告