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

Kết hợp $set và $push trong một lệnh update MongoDB

Có thể dùng nhiều toán tử update ($set, $push, $inc...) cùng lúc trong một lệnh update().

Tạo collection dem0143:

> db.dem0143.insertOne({"StudentId":1,"Details":{"Name":"Chris"}});
> db.dem0143.insertOne({"StudentId":2,"Details":{"Name":"David"}});

Cập nhật document _id cụ thể: $push thêm StudentAge, $set đổi Details.Name:

> db.dem0143.update(
   {_id: ObjectId("5e32eba5fdf09dd6d08539b8")},
   {$push: {StudentAge:21}, $set: {"Details.Name":"John Doe"}}
);

Kết quả: Name đổi thành John Doe, mảng StudentAge có thêm 21:

{
   "_id" : ObjectId("5e32eba5fdf09dd6d08539b8"),
   "StudentId" : 2,
   "Details" : {"Name" : "John Doe"},
   "StudentAge" : [21]
}