Vấn đề
Cần cập nhật (push) giá trị mới vào 2 mảng riêng biệt trong cùng một document MongoDB chỉ với 1 lệnh update.
Giải pháp: Sử dụng toán tử $push
Toán tử $push cho phép thêm phần tử vào mảng. Có thể chỉ định nhiều trường mảng trong cùng một đối tượng update.
Ví dụ minh họa
1. Tạo collection và dữ liệu
> db.twoSeparateArraysDemo.insertOne({"StudentName":"Larry","StudentFirstGameScore":[98],"StudentSecondGameScore":[77]});
> db.twoSeparateArraysDemo.insertOne({"StudentName":"Mike","StudentFirstGameScore":[58],"StudentSecondGameScore":[78]});
> db.twoSeparateArraysDemo.insertOne({"StudentName":"David","StudentFirstGameScore":[65],"StudentSecondGameScore":[67]});
2. Xem dữ liệu ban đầu
> db.twoSeparateArraysDemo.find().pretty();
3. Cập nhật 2 mảng trong 1 lệnh
> db.twoSeparateArraysDemo.update(
{_id:ObjectId("5c9b152d15e86fd1496b38b9")},
{$push: {StudentFirstGameScore: 45, StudentSecondGameScore: 99}}
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
4. Kiểm tra kết quả
> db.twoSeparateArraysDemo.find().pretty();
Kết quả: Document của Mike giờ có StudentFirstGameScore: [58, 45] và StudentSecondGameScore: [78, 99]. Các document khác không thay đổi.
Lưu ý
$pushthêm phần tử vào cuối mảng.- Có thể kết hợp với
$eachđể thêm nhiều phần tử cùng lúc:{$push: {field: {$each: [val1, val2]}}}. - Dùng
updateOnehoặcupdateManythay choupdate(deprecated) trong các phiên bản MongoDB mới.