开发者

How to batch update documents on the server in MongoDB using calculated values?

I have a collection of things, each thing has some user reviews and each review has a numeric (1-5) rating. I would like to periodically run a batch job that will calculate the average rating for each "thing" based on individual ratings in that thing's user reviews and will then save the "thing" again with that new rating. I would like that to happen on the server without the need to download and upload each document.

In other words, I am looking for a solution that will iterate over all things in my collection, sum the ratings from the user reviews then divide that sum by the count of ratings (thus getting the average) and store that average in a property of each document.

I tried approaching this with a map/reduce at first, something like:

function () {
    var rating = 0;
    for (var i = 0; i < this.Reviews.length; i++) {
        rating += this.Reviews[i].Rating;
    }
    rating 开发者_开发知识库= rating / this.Reviews.length;
    emit(this._id, rating);
}

function(key, values) {
    return null;
}

The ratings seem to be calculated properly, but I was unable to call db.things.update() inside either the first or the second function. I was able to update the ratings by using the resulting table like so:

db.reduced.find().forEach(function(thing) {
  db.things.update({_id: thing._id},{$set:{Rating:thing.value}});
});

But this is a client side solution which is not satisfactory... It doesn't have to be map/reduce, but probably that is the way to go?


Use db.eval( your_JS_code_here ).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜