No need for another query, you can still run the same aggregate operation but this time adding another pipeline that uses the $lookup operator which pipes the results from the previous $group pipeline to do a left join on the user collection:
db.table_name.aggregate([
{
"$group": {
"_id": "$userId",
"avgRating": { "$avg": "$rating" }
}
},
{
"$lookup": {
"from": "user",
"localField": "_id",
"foreignField": "_id",
"as": "users"
}
}
])
If your MongoDB version does not support the $lookup operator, then you will need two queries, run as follows:
var cursor = db.table_name.aggregate([
{
"$group": {
"_id": "$userId",
"avgRating": { "$avg": "$rating" }
}
}
]);
var results = cursor.map(function(doc){
var user = db.users.findOne({ "_id": doc._id })
return {
user: user,
avgRating: doc.avgRating
};
});
printjson(results);