Node.JS + MongoDB聚合框架的平均值

Ros*_*s J 1 mongodb node.js aggregation-framework

我一直在考虑使用Node和MongoDb作为Android应用程序的评级系统,到目前为止,我已经实现了创建,更新和删除,但是如果我想从平均评级中获取平均评级,该怎么办? D B.这是我给出的数据结构决定:

[
  {
    "_id": "1",
    "ratings": [
      {
        "value": "5",
        "user": "CoolUser1"
      },
      {
        "value": "4",
        "user": "CoolUser2"
      }
    ]
  },
  {
    "_id": "2",
    "ratings": [
      {
        "value": "4",
        "user": "CoolUser3"
      },
      {
        "value": "2",
        "user": "CoolUser4"
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

基本上我需要的是给定_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);
                            }
                        }
        );
}
Run Code Online (Sandbox Code Playgroud)

use*_*268 9

存储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();
});
Run Code Online (Sandbox Code Playgroud)