Reputation: 4088
The query below increases score
by one
.
db.people.findAndModify({
query: { name: "Andy" },
update: { $inc: { score: 1 } }
})
But, is it possible to do more than just increase the score
. I would like to, increase the score
and also compute avg_field
for same document.
db.people.findAndModify({
query: { name: "Andy" },
update: { $inc: { score: 1 }, avg_field : {x divide by new score value} }
})
I might be able to use function to compute all that, but still that will not help inserting updated values. I would like to keep the operation atomic and hence trying to update in the same query.
Suggestions?
Upvotes: 0
Views: 213
Reputation: 48526
Maybe you could do it through aggregatioin
, with operator $add
and $divide
as below. However, the aggregation does not update the document, so you should return the cursor from aggregation, then update the document one by one. Here are the sample codes.
// 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}});
});
Upvotes: 1