如何使用计算值批量更新MongoDB服务器上的文档?

发布于 2024-11-07 05:27:34 字数 842 浏览 1 评论 0原文

我有一些东西的集合,每个东西都有一些用户评论,每个评论都有一个数字(1-5)评级。我想定期运行一个批处理作业,该作业将根据每个“事物”的用户评论中的个人评级计算平均评级,然后使用新的评级再次保存“事物”。我希望这发生在服务器上,而不需要下载和上传每个文档。

换句话说,我正在寻找一种解决方案,该解决方案将迭代我的集合中的所有内容,将用户评论的评分相加,然后将该总和除以评分数(从而获得平均值)并将该平均值存储在属性中每个文件。

我首先尝试使用 map/reduce 来解决这个问题,例如:

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;
}

评级似乎计算正确,但我无法在第一个或第二个函数中调用 db.things.update() 。我能够通过使用结果表来更新评级,如下所示:

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

但这是一个客户端解决方案,并不令人满意......它不一定是map/reduce,但可能是这样该怎么走?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我们的影子 2024-11-14 05:27:34

使用 db.eval( your_JS_code_here )。

Use db.eval( your_JS_code_here ).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文