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

Cách tăng giá trị bên trong hàm update() trong MongoDB

Sử dụng toán tử $inc để tăng giá trị. Trước hết, tạo collection với tài liệu mẫu:

> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Chris","PlayerScore":78});
{ "acknowledged": true, "insertedId": ObjectId("5cd2b3f4345990cee87fd893") }
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"Robert","PlayerScore":88});
{ "acknowledged": true, "insertedId": ObjectId("5cd2b3fc345990cee87fd894") }
> db.addInUpdateFunctionDemo.insertOne({"PlayerName":"David","PlayerScore":99});
{ "acknowledged": true, "insertedId": ObjectId("5cd2b407345990cee87fd895") }

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

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

Kết quả:

{
    "_id": ObjectId("5cd2b3f4345990cee87fd893"),
    "PlayerName": "Chris",
    "PlayerScore": 78
}
{
    "_id": ObjectId("5cd2b3fc345990cee87fd894"),
    "PlayerName": "Robert",
    "PlayerScore": 88
}
{
    "_id": ObjectId("5cd2b407345990cee87fd895"),
    "PlayerName": "David",
    "PlayerScore": 99
}

Thực hiện tăng giá trị trong update()

> db.addInUpdateFunctionDemo.update(
    {_id: ObjectId("5cd2b407345990cee87fd895")},
    {$inc: {PlayerScore: 201}}
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Kiểm tra lại

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

Kết quả (điểm của David tăng từ 99 lên 300):

{
    "_id": ObjectId("5cd2b3f4345990cee87fd893"),
    "PlayerName": "Chris",
    "PlayerScore": 78
}
{
    "_id": ObjectId("5cd2b3fc345990cee87fd894"),
    "PlayerName": "Robert",
    "PlayerScore": 88
}
{
    "_id": ObjectId("5cd2b407345990cee87fd895"),
    "PlayerName": "David",
    "PlayerScore": 300
}

Mẹo: Toán tử $inc cũng chấp nhận giá trị âm để giảm giá trị trường.