Giả sử, ở đây chúng tôi đang tăng StudentScores cho MongoDB nằm trong StudentDetails -
... "StudentScores": {
... "StudentMathScore": 90,
... "StudentMongoDBScore": 78
... } Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.embeddedValueIncrementDemo.insertOne(
... {
... "StudentDetails": {
... "StudentScores": {
... "StudentMathScore": 90,
... "StudentMongoDBScore": 78
... }
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd2b670345990cee87fd896")
} 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.embeddedValueIncrementDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails" : {
"StudentScores" : {
"StudentMathScore" : 90,
"StudentMongoDBScore" : 78
}
}
} Sau đây là truy vấn để tăng giá trị nhúng. Ở đây, chúng tôi đang tăng StudentMongoDBScore -
> db.embeddedValueIncrementDemo.update({ _id: new ObjectId("5cd2b670345990cee87fd896") }, { $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } }, { upsert: true, safe: true }, null);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Hãy để chúng tôi kiểm tra tất cả các tài liệu một lần nữa -
> db.embeddedValueIncrementDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau -
{
"_id" : ObjectId("5cd2b670345990cee87fd896"),
"StudentDetails" : {
"StudentScores" : {
"StudentMathScore" : 90,
"StudentMongoDBScore" : 98
}
}
}