【问题标题】:Node.JS + MongoDB aggregation framework average valueNode.JS + MongoDB 聚合框架平均值
【发布时间】:2013-02-05 21:27:27
【问题描述】:

我一直在考虑将 Node 和 MongoDb 用于 Android 应用的评分系统,到目前为止,我已经很好地实现了 Create、Update 和 Delete,但是当我想获得平均评分时我不知道该怎么做从数据库回来。这是我决定的数据结构:

[
  {
    "_id": "1",
    "ratings": [
      {
        "value": "5",
        "user": "CoolUser1"
      },
      {
        "value": "4",
        "user": "CoolUser2"
      }
    ]
  },
  {
    "_id": "2",
    "ratings": [
      {
        "value": "4",
        "user": "CoolUser3"
      },
      {
        "value": "2",
        "user": "CoolUser4"
      }
    ]
  }
]

基本上我需要的是给定 _id 的评分平均值。

这是我用来了解我如何设置 mongoDB 连接的 Update 方法:

exports.updateRating = function(req, res) {
    var id = req.params.id;
    var rating = req.body;
    console.log('Updating a rating: ' + id);
    console.log(JSON.stringify(rating));
        ratings.update({'_id': id}, 
                        {$push: rating}, 
                        {upsert:true}, 
                        function(err, result) {
                            if (err) {
                                console.log('Error updating rating: ' + err);
                                res.send({'error':'An error has occurred'});
                            } else {
                                console.log('' + result + ' document(s) updated');
                                res.send(rating);
                            }
                        }
        );
}

【问题讨论】:

    标签: node.js mongodb aggregation-framework


    【解决方案1】:

    ratings.value 存储为字符串是否重要?

    这会起作用,但前提是您在安全之前将rating 转换为数字

    ratings.aggregate([
       { $match: { _id: id } },
       { $unwind: '$ratings' },
       { $group: { _id: null, avg: { $avg: '$ratings.value' } } }
    ], function(err, result) {
        console.log(result);
        db.close();
    });
    

    【讨论】:

    • 想想你,当我将评分存储为数字时效果很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-05
    • 2015-03-29
    相关资源
    最近更新 更多