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

Cập nhật mảng chuỗi lồng trong mảng object MongoDB ($pull + $[])

Để xóa một giá trị cụ thể (ví dụ: "Mike") khỏi **tất cả các mảng con** (nested arrays) bên trong một mảng object, MongoDB 3.6+ cung cấp **All Positional Operator $[]** kết hợp với $pull. Cú pháp: 'parentArray.$[].nestedArray' duyệt qua tất cả phần tử của parentArray.

1. Tạo dữ liệu: Information1 là mảng object, mỗi object có mảng Information2 (chuỗi)

> db.demo412.insertOne({
    "Information1": [
        { "Information2": ["John", "David"] },
        { "Information2": ["Mike"] }
    ]
});
{ "acknowledged": true, "insertedId": ObjectId("5e70f38b15dc524f70227683") }

2. Xem dữ liệu

> db.demo412.find();

Kết quả: 2 object trong Information1, Information2 chứa ["John","David"] và ["Mike"].

3. Xóa "Mike" khỏi TẤT CẢ mảng Information2 (dùng $[])

> db.demo412.updateMany(
    { _id: ObjectId("5e70f38b15dc524f70227683") },
    { $pull: { 'Information1.$[].Information2': "Mike" } }
);
{ "acknowledged": true, "matchedCount": 1, "modifiedCount": 1 }

Giải thích: Information1.$[].Information2 -> `$[]` duyệt **tất cả** object trong Information1, truy cập mảng Information2 của mỗi object, $pull xóa "Mike".

4. Kết quả

> db.demo412.find();

Kết quả:

{ "_id": ObjectId("..."), "Information1": [
    { "Information2": ["John", "David"] },
    { "Information2": [] }   // Mike đã bị xóa, mảng rỗng
] }

Các biến thể:

  • Chỉ xóa trong phần tử **đầu tiên** khớp điều kiện: Dùng $ (Positional) + arrayFilters.
  • Xóa theo điều kiện phức tạp trong nested array: Dùng arrayFilters với $[identifier].