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

Cách xóa phần tử mảng theo index trong MongoDB

Để xóa phần tử mảng theo vị trí (index) trong MongoDB, bạn cần thực hiện 2 bước: dùng $unset đặt null tại vị trí đó, sau đó dùng $pull xóa các giá trị null.

Quy trình 2 bước

Bước 1: Đặt null tại index cần xóa

db.yourCollectionName.update({}, {$unset : {"yourArrayFieldName.yourIndexValue" : 1 }});

Bước 2: Xóa các giá trị null khỏi mảng

db.yourCollectionName.update({}, {$pull : {"yourArrayFieldName" : null}});

Ví dụ minh họa

Tạo collection và dữ liệu

> db.removeArrayElementByItsIndexDemo.insertOne({"InstructorName":"David", "InstructorAge":28,"InstructorSubject":["MongoDB","MySQL","Java","SQL Server","PL/SQL"]});
{ "acknowledged" : true, "insertedId" : ObjectId("5c8abbfc6cea1f28b7aa0803") }

Xem dữ liệu ban đầu

> db.removeArrayElementByItsIndexDemo.find().pretty();
{
    "_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"),
    "InstructorName" : "David",
    "InstructorAge" : 28,
    "InstructorSubject" : [ "MongoDB", "MySQL", "Java", "SQL Server", "PL/SQL" ]
}

Mảng có các index: 0=MongoDB, 1=MySQL, 2=Java, 3=SQL Server, 4=PL/SQL

Bước 1: Unset index 2 (phần tử "Java")

> db.removeArrayElementByItsIndexDemo.update({}, {$unset : {"InstructorSubject.2" : 1 }});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Bước 2: Pull null values

> db.removeArrayElementByItsIndexDemo.update({}, {$pull : {"InstructorSubject" : null}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra kết quả

> db.removeArrayElementByItsIndexDemo.find().pretty();
{
    "_id" : ObjectId("5c8abbfc6cea1f28b7aa0803"),
    "InstructorName" : "David",
    "InstructorAge" : 28,
    "InstructorSubject" : [ "MongoDB", "MySQL", "SQL Server", "PL/SQL" ]
}

Phần tử "Java" (index 2) đã bị xóa hoàn toàn, mảng còn 4 phần tử.

Lưu ý quan trọng

  • Index trong MongoDB bắt đầu từ 0
  • $unset chỉ đặt null, không xóa phần tử → mảng sẽ có "lỗ" (null)
  • $pull với null xóa tất cả phần tử null trong mảng
  • Cách này áp dụng cho mảng giá trị đơn giản (string, number) và mảng object

Cách thay thế (MongoDB 3.6+)

Sử dụng $arrayElemAt trong aggregation hoặc $slice nhưng phức tạp hơn. Cách 2 bước trên là phổ biến và dễ hiểu nhất.