Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MongoDB

Truy vấn MongoDB xóa tài liệu con khỏi tài liệu cha

Để xóa một tài liệu con (subdocument) khỏi tài liệu cha, hãy sử dụng toán tử $pull kết hợp với phương thức update(). Trước tiên, hãy tạo một collection với tài liệu mẫu:

> db.demo538.insertOne(
... {
...     id:101,
...     "details" :
...     {
...         anotherDetails:
...         [
...             {
...                 "Name":"Chris",
...                 Age:21
...             },
...             {
...                 "Name":"David",
...                 Age:23
...             },
...             {
...                 "Name":"Bob",
...                 Age:20
...             }
...         ]
...     }
... }
... );
{ "acknowledged" : true, "insertedId" : ObjectId("5e8c8f0aef4dcbee04fbbc08") }

Hiển thị tất cả tài liệu:

> db.demo538.find();

Kết quả:

{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "David", "Age" : 23 }, { "Name" : "Bob", "Age" : 20 } ] } }

Truy vấn xóa tài liệu con có Age: 23:

> db.demo538.update({ id:101}, {$pull : { "details.anotherDetails" : {"Age":23} } })
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra lại sau khi xóa:

> db.demo538.find();

Kết quả:

{ "_id" : ObjectId("5e8c8f0aef4dcbee04fbbc08"), "id" : 101, "details" : { "anotherDetails" : [ { "Name" : "Chris", "Age" : 21 }, { "Name" : "Bob", "Age" : 20 } ] } }