Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.JS + MongoDB aggregation framework average value

Node.JS + MongoDB aggregation framework average value

Problem

I have been thinking of using Node and MongoDb for a ratings system for an Android app, so far I have implemented Create, Update and Delete fine but am at a loss as to what to do when I want to get the average rating back from the DB. Here is the data structure I gave decided upon:

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

Basically what I need is the average value in ratings for a given _id.

Here is the Update method I am using to give a sense of how I have setup the mongoDB connection:

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);
                            }
                        }
        );
}
Problem courtesy of: Ross J

Solution

Is it critical to store ratings.value as a string?

This will work, but only if you convert rating to number before safe

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

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.JS + MongoDB aggregation framework average value

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×