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

Chèn phần tử vào mảng bên trong object trong MongoDB

Thêm phần tử vào mảng lồng trong object với $push

Sử dụng $push kết hợp dot notation để chèn phần tử mới vào mảng nằm sâu trong object.

1. Tạo collection với cấu trúc phức tạp

> db.demo449.insertOne({
    details1: {
        details2: [{ _id: new ObjectId(), Name: "Chris" }],
        details3: [{ _id: new ObjectId(), Name: "David" }]
    }
});
{ "acknowledged": true, "insertedId": ObjectId("5e7a40e971f552a0ebb0a6e3") }

2. Xem dữ liệu ban đầu

> db.demo449.find();
{
    "_id": ObjectId("5e7a40e971f552a0ebb0a6e3"),
    "details1": {
        "details2": [{ "_id": ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name": "Chris" }],
        "details3": [{ "_id": ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name": "David" }]
    }
}

3. Thêm "Carol" vào details1.details2

> db.demo449.update(
    { _id: ObjectId("5e7a40e971f552a0ebb0a6e3") },
    { $push: { 'details1.details2': { _id: ObjectId(), "Name": "Carol" } } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

4. Kết quả sau cập nhật

> db.demo449.find();
{
    "_id": ObjectId("5e7a40e971f552a0ebb0a6e3"),
    "details1": {
        "details2": [
            { "_id": ObjectId("5e7a40e971f552a0ebb0a6e1"), "Name": "Chris" },
            { "_id": ObjectId("5e7a41a671f552a0ebb0a6e5"), "Name": "Carol" }
        ],
        "details3": [{ "_id": ObjectId("5e7a40e971f552a0ebb0a6e2"), "Name": "David" }]
    }
}

Lưu ý quan trọng

  • Sử dụng single quotes cho đường dẫn có dấu chấm: 'details1.details2'
  • $push thêm vào cuối mảng. Dùng $position để chèn ở vị trí cụ thể
  • Với MongoDB 4.2+, khuyến nghị dùng updateOne() thay update()