Bạn có thể sử dụng toán tử $ set cho việc này. Cú pháp như sau -
db.yourCollectionName.update({}, { $set : {"yourFieldName": [] }} , {multi:true} ); Để hiểu cú pháp trên, chúng ta hãy tạo một bộ sưu tập với tài liệu. Truy vấn để tạo một bộ sưu tập với một tài liệu như sau -
> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Larry","InstructorTechnicalSubject":["Java","MongoDB"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fb971d3c9d04998abf00e")
}
> db.deleteAllElementsInArrayDemo.insertOne({"InstructorName":"Mike","InstructorTechnicalSubject":["C","C++","Python"]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c8fb98ad3c9d04998abf00f")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find (). Truy vấn như sau -
> db.deleteAllElementsInArrayDemo.find().pretty();
Sau đây là kết quả -
{
"_id" : ObjectId("5c8fb971d3c9d04998abf00e"),
"InstructorName" : "Larry",
"InstructorTechnicalSubject" : [
"Java",
"MongoDB"
]
}
{
"_id" : ObjectId("5c8fb98ad3c9d04998abf00f"),
"InstructorName" : "Mike",
"InstructorTechnicalSubject" : [
"C",
"C++",
"Python"
]
} Đây là truy vấn để xóa tất cả các phần tử trong trường mảng -
> db.deleteAllElementsInArrayDemo.update({}, { $set : {"InstructorTechnicalSubject": [] }} , {multi:true} );
WriteResult({ "nMatched" : 2, "nUpserted" : 0, "nModified" : 2 }) Bây giờ chúng ta hãy kiểm tra tất cả các tài liệu từ một bộ sưu tập bằng cách sử dụng find (). Truy vấn như sau -
> db.deleteAllElementsInArrayDemo.find().pretty();
Sau đây là kết quả đầu ra. Chúng tôi đã xóa tất cả các phần tử của trường mảng “CoachTechnicalSubject”:
{
"_id" : ObjectId("5c8fb971d3c9d04998abf00e"),
"InstructorName" : "Larry",
"InstructorTechnicalSubject" : [ ]
}
{
"_id" : ObjectId("5c8fb98ad3c9d04998abf00f"),
"InstructorName" : "Mike",
"InstructorTechnicalSubject" : [ ]
}