MongoDB.live, free & fully virtual. June 9th - 10th. Register Now MongoDB.live, free & fully virtual. June 9th - 10th. Register Now

Aggregate Pipeline Method Help

Hello,

I have a database with over 1000 reviews of products, I need to find all of the people with at least 3 reviews, and I need to show their reviewer ID, reviewer name, and the number of reviews they’ve written

I understand that I have to use an aggregate method but I am very confused on how to do it, so any help would be appreciated

If you are configured confused with aggregation, my best advice is to take the free M121 course from MongoDB university. If your data is spread into more than one collection then the aggregation stage $lookup will be useful. The $group stage could also come in handy to group reviews by reviewer.

1 Like

Thanks ill look into it

MongoDB database data can be queried can be queried in different ways to get the data you want and in the required format.

When there is a need for something like

it is the Aggregation query. With aggregation query, the collection’s documents are processed through stages (together called as pipeline) to get the desired output.

For example, in this case, (1) it is grouping by people and counting, (2) matching (the count is at least 3), and finally, (3) projecting the required fields (reviewer ID, reviewer name, and the number of reviews).

The aggregation pipeline stages in this case are: $group, $match and the $project (or $addFields). Aggregation Pipeline Quick Reference has links to the stages and examples.

Also, MongoDB Compass GUI tool has this Aggregation TAB, where one can build the query using GUI (like list boxes and buttons). A nice feature with this is as you build each stage, you can see the transformed data at that stage in an adjacent window (and it will be input to the next stage in the pipeline).

Sounds like you want something like this:

db.coll.aggregate([{$group:{
    _id:"$reviewerID",
    name:{$first:"reviewerName"}.
    count:{$sum:1}
}},
{$match:{
    count:{$gt:2}
}}
])
2 Likes

Thanks but does not work

It cannot work as is because the field names in your collection are not the same. From your screenshot in https://discourse.university.mongodb.com/t/aggregate-pipeline-help/47329?u=steevej-1495 it looks like your fields start with an underline and may be another character (the d is _id) that you did not include.