Đối với cập nhật có điều kiện, hãy sử dụng update () và đặt giá trị mới bằng cách sử dụng $ set. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo150.insertOne({"StudentId":101,"StudentName":"Chris","StudentMarks":35});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e350dcdfdf09dd6d08539d3")
}
> db.demo150.insertOne({"StudentId":102,"StudentName":"Chris","StudentMarks":55});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e350dcefdf09dd6d08539d4")
}
> db.demo150.insertOne({"StudentId":103,"StudentName":"David","StudentMarks":34});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e350dcffdf09dd6d08539d5")
}
> db.demo150.insertOne({"StudentId":104,"StudentName":"Chris","StudentMarks":38});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e350dd0fdf09dd6d08539d6")
} Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo150.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"), "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35 }
{ "_id" : ObjectId("5e350dcefdf09dd6d08539d4"), "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55 }
{ "_id" : ObjectId("5e350dcffdf09dd6d08539d5"), "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 34 }
{ "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"), "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38 } Sau đây là truy vấn cập nhật có điều kiện tùy thuộc vào trường phù hợp -
> db.demo150.update({"StudentId":103},{$set:{"StudentMarks":97}});
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find () -
> db.demo150.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5e350dcdfdf09dd6d08539d3"), "StudentId" : 101, "StudentName" : "Chris", "StudentMarks" : 35 }
{ "_id" : ObjectId("5e350dcefdf09dd6d08539d4"), "StudentId" : 102, "StudentName" : "Chris", "StudentMarks" : 55 }
{ "_id" : ObjectId("5e350dcffdf09dd6d08539d5"), "StudentId" : 103, "StudentName" : "David", "StudentMarks" : 97 }
{ "_id" : ObjectId("5e350dd0fdf09dd6d08539d6"), "StudentId" : 104, "StudentName" : "Chris", "StudentMarks" : 38 }