Search code examples
mongodbmongooseaggregationmongoose-populate

Populating a field by aggregating other collections


I have a user and a ratings collection. Ratings collection has ratedBy, ratedTo and score. Now I want to find all users on some criteria and also getting their ratingAvg. So the result would look something like the following:

[
{_id: 44s5dsdde4e4e55e,name:"bob", email: "bob@gmail.com", ratingAvg: 3, ...},
{_id: 3as5dsdde4e4e55e,name:"alice", email: "alice@gmail.com", ratingAvg: 4, ...}
]

I am very new to databases and especially MongoDB. I can find the ratingAvg of a particular user by doing this

Ratings.aggregate([
            {
                $match: {ratedTo: Mongoose.Types.ObjectId(userId)}
            }, 
            {
                $group: {
                    _id: "$ratedTo",
                    avgRating: { $avg : "$score" }
                }
            }
        ]);

But what I need to do this is to get the users with their fields and ratingAvg calculated like above. What I can think of is to find the users separately by Users.find({field: criteria}) and loop over them and use the above code to find their ratings. Or the solution would be to do a lookup and join users and ratings and then aggregate them.


Solution

  • One possible way is to use aggregation with:

    Playground