MongoDB:在更新语句中使用$ inc

时间:2013-11-21 06:00:24

标签: mongodb

我在mongoDB中有一个Collection,其中有许多文档,其中一个看起来像:

{
"_id" : ObjectId("525c22348771ebd7b179add8"),
"clear" : "YES",
"cust_id" : "A1234",
"score" : 500,
"status" : "A"
}

我编写了一个mongo Shell代码来获取状态为“A”的所有cust_id的cust_id和得分总和

cust_to_clear=db.aggregation.aggregate(
    {$match:{status:'A'}},
    {$group:{_id:'$cust_id',total:{$sum:'$score'}}})

以上代码给出了如下结果:

{
"result" : [ 
    {
        "_id" : "A4567",
        "total" : 600
    }, 
    {
        "_id" : "A3456",
        "total" : 1400
    }, 
    {
        "_id" : "A2345",
        "total" : 301
    }, 
    {
        "_id" : "A1234",
        "total" : 800
    }
],
"ok" : 1
}

我的要求是将从上面的结果中获取的所有cust_id的得分更新为得分+100。 请建议我如何在mongo Shell中编写需求?

我的方法:

cust_to_clear.result.forEach(
    function(x){
     db.aggregation.update({cust_id:x._id},{$set:{score:{$inc:{$score:100}}}}, {multi: true})}
     )

预期产出:

{
"_id" : ObjectId("525c22348771ebd7b179add8"),
"clear" : "YES",
"cust_id" : "A1234",
"score" : 600,
"status" : "A"
}

提前致谢:)

1 个答案:

答案 0 :(得分:1)

db.aggregation.update({ cust_id : x._id }, { $inc : { 'score' : 100 }}, {multi: true});