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

Xóa đối tượng khỏi mảng trong MongoDB

Dùng toán tử $pull để xóa đối tượng khỏi mảng. Cú pháp:

db.yourCollectionName.update( {'_id':ObjectId("...")}, {$pull:{"yourArrayName":{"yourArrayFieldName":yourValue}}}, false, true);

Tạo collection removeObject:

> db.removeObject.insertOne({"CustomerName":"Maxwell","CustomerAge":23, "CustomerDetails":[ {"CustomerId":100,"CustomerProduct":"Product-1"}, {"CustomerId":150,"CustomerProduct":"Product-2"}, {"CustomerId":200,"CustomerProduct":"Product-3"} ] });
{ "acknowledged" : true, "insertedId" : ObjectId("5c6ea036a0c51185aefbd14f") }

Hiển thị:

> db.removeObject.find().pretty();

Xóa phần tử CustomerId = 150:

> db.removeObject.update( {'_id':ObjectId("5c6ea036a0c51185aefbd14f")}, {$pull:{"CustomerDetails":{"CustomerId":150}}}, false, true);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra: CustomerId 150 đã bị xóa khỏi mảng CustomerDetails.