2016-02-28 72 views
0

以下查詢通過one增加score查詢和更新Mongo文檔

db.people.findAndModify({ 
    query: { name: "Andy" }, 
    update: { $inc: { score: 1 } } 
}) 

但是,是否有可能做的不僅僅是增加score。我想增加score並且同樣計算avg_field

db.people.findAndModify({ 
    query: { name: "Andy" }, 
    update: { $inc: { score: 1 }, avg_field : {x divide by new score value} } 
}) 

我可能能夠使用函數來計算所有這些,但仍然不會幫助插入更新的值。我想保持操作原子,因此試圖在同一個查詢中更新。

對此提出建議?

回答

1

也許你可以通過aggregatioin來完成,運營商$add$divide如下。但是,聚合不會更新文檔,所以您應該從聚合中返回光標,然後逐個更新文檔。這裏是示例代碼。

// increase score than compute the avg_field, then return the cursor. 
var cur = db.people.aggregate([ 
    {$match: { name: "Andy" }}, 
    { "$project": 
     { 
      "_id": "$_id", 
      "score": {$add: ['$score', 1]}, // add score by 1 
      "avg_field": {$divide: ['$v1', {$add: ['$score', 1]}]} // compute the new avg_field 
     } 
    } 
]); 

// Iterate through results and update each people. 
cur.forEach(function(doc) { 
    var doc = cur.next(); 
    db.people.update({ _id: doc._id }, 
        { "$set": { avg_field: doc.avg_field, score: doc.score}}); 
}); 
+0

這不是一個壞主意。我喜歡。 –