Để tăng một giá trị trong đối tượng lồng nhau, bạn có thể sử dụng toán tử $ inc. Trước tiên, hãy để chúng tôi triển khai truy vấn sau để tạo một bộ sưu tập với các tài liệu
>db.incrementValueDemo.insertOne({"StudentName":"Larry","StudentCountryName":"US","StudentDetails":[{"StudentSubjectName":"Math","StudentMathMarks":79}]});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c986ca0330fd0aa0d2fe4a2")
} Sau đây là truy vấn để 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.incrementValueDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
"StudentName" : "Larry",
"StudentCountryName" : "US",
"StudentDetails" : [
{
"StudentSubjectName" : "Math",
"StudentMathMarks" : 79
}
]
} Sau đây là truy vấn để tăng một giá trị trong đối tượng lồng nhau. Điểm sẽ được tăng dần ở đây
> db.incrementValueDemo.update( {"StudentDetails.StudentSubjectName":"Math"}, { $inc : {
"StudentDetails.$.StudentMathMarks" : 1 } });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Sau đây là truy vấn để kiểm tra giá trị có được tăng lên hay không
> db.incrementValueDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c986ca0330fd0aa0d2fe4a2"),
"StudentName" : "Larry",
"StudentCountryName" : "US",
"StudentDetails" : [
{
"StudentSubjectName" : "Math",
"StudentMathMarks" : 80
}
]
}