Dùng $set gán mảng rỗng. Tạo collection:
> db.pullAllElementDemo.insertOne(
{
"StudentId":101,
"StudentDetails" : [
{ "StudentName": "Carol", "StudentAge":21, "StudentCountryName":"US" },
{ "StudentName": "Chris", "StudentAge":24, "StudentCountryName":"AUS" }
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ccdd9c8685b30d09a7111e4") }
> db.pullAllElementDemo.insertOne(
{
"StudentId":102,
"StudentDetails" : [
{ "StudentName": "Robert", "StudentAge":27, "StudentCountryName":"UK" },
{ "StudentName": "David", "StudentAge":23, "StudentCountryName":"US" }
]
}
);
{ "acknowledged" : true, "insertedId" : ObjectId("5ccdd9f7685b30d09a7111e5") }
Hiển thị tất cả:
> db.pullAllElementDemo.find().pretty();
Xóa toàn bộ mảng StudentDetails của StudentId=102:
> db.pullAllElementDemo.update( {StudentId:102}, { "$set": { "StudentDetails": [] }} );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
Kiểm tra lại (mảng rỗng):
> db.pullAllElementDemo.find().pretty();
Kết quả: