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

Tăng giá trị trường lồng nhau trong tài liệu MongoDB

Giả sử chúng ta cần tăng điểm StudentScores cho MongoDB, trường này nằm bên trong StudentDetails:

... "StudentScores": { ... "StudentMathScore": 90, ... "StudentMongoDBScore": 78 ... }

Tạo collection với tài liệu mẫu

> db.embeddedValueIncrementDemo.insertOne(
    {
        "StudentDetails": {
            "StudentScores": {
                "StudentMathScore": 90,
                "StudentMongoDBScore": 78
            }
        }
    }
);
{ "acknowledged": true, "insertedId": ObjectId("5cd2b670345990cee87fd896") }

Hiển thị tất cả tài liệu

> db.embeddedValueIncrementDemo.find().pretty();

Kết quả:

{
    "_id": ObjectId("5cd2b670345990cee87fd896"),
    "StudentDetails": {
        "StudentScores": {
            "StudentMathScore": 90,
            "StudentMongoDBScore": 78
        }
    }
}

Tăng giá trị trường lồng nhau

Sử dụng toán tử $inc kết hợp với dấu chấm (dot notation) để truy cập trường sâu:

> db.embeddedValueIncrementDemo.update(
    { _id: new ObjectId("5cd2b670345990cee87fd896") },
    { $inc: { "StudentDetails.StudentScores.StudentMongoDBScore": 20 } },
    { upsert: true, safe: true },
    null
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Kiểm tra kết quả

> db.embeddedValueIncrementDemo.find().pretty();

Kết quả sau khi cập nhật (điểm MongoDB tăng từ 78 lên 98):

{
    "_id": ObjectId("5cd2b670345990cee87fd896"),
    "StudentDetails": {
        "StudentScores": {
            "StudentMathScore": 90,
            "StudentMongoDBScore": 98
        }
    }
}

Lưu ý: Cú pháp update() ở trên là phiên bản cũ. Trong MongoDB 3.2+, nên sử dụng updateOne() hoặc updateMany() thay thế.