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);
}
}
);
}
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();
});
Discussion
View additional discussion.