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

Cập nhật tài liệu MongoDB: Thêm phần tử mới vào mảng

Để thêm phần tử vào mảng, sử dụng toán tử $push.

Ví dụ: Collection updateDemo chứa sinh viên và môn học.

> db.updateDemo.insertOne({"StudentName":"Larry","StudentCoreSubject":["Java","C"]});
> db.updateDemo.insertOne({"StudentName":"Robert","StudentCoreSubject":["C++","MongoDB"]});
> db.updateDemo.insertOne({"StudentName":"Chris","StudentCoreSubject":["Python"]});

Xem dữ liệu:

> db.updateDemo.find().pretty();

Kết quả:

{ "_id" : ObjectId(...), "StudentName" : "Larry", "StudentCoreSubject" : ["Java", "C"] }
{ "_id" : ObjectId(...), "StudentName" : "Robert", "StudentCoreSubject" : ["C++", "MongoDB"] }
{ "_id" : ObjectId(...), "StudentName" : "Chris", "StudentCoreSubject" : ["Python"] }

Thêm "MySQL" vào mảng của Larry:

> db.updateDemo.update(
    { _id: ObjectId("5c98ba78330fd0aa0d2fe4c9") },
    { $push: { "StudentCoreSubject": "MySQL" } }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Kiểm tra lại:

> db.updateDemo.find().pretty();

Kết quả:

{ "_id" : ObjectId(...), "StudentName" : "Larry", "StudentCoreSubject" : ["Java", "C", "MySQL"] }
{ "_id" : ObjectId(...), "StudentName" : "Robert", "StudentCoreSubject" : ["C++", "MongoDB"] }
{ "_id" : ObjectId(...), "StudentName" : "Chris", "StudentCoreSubject" : ["Python"] }

Mở rộng: Dùng $push với $each để thêm nhiều phần tử cùng lúc, hoặc $addToSet để tránh trùng lặp.