'Mongodb how to count how many times a field value comes?
let´s say I have a document of blog posts that has fields "_id, userName, age". a user could have made more than one blog post, I want to find the users that have made 4 posts. db.blogs.aggregate([{$group: {_id: {"$userName", "age"}, : {$sum: ""eq", 3}}])
Solution 1:[1]
To know how many times a field comes, use a $group stage to group by that field and add an extra field for the count using the $count operator. Then if you want to filter by that count, just add a $match stage to filter by that new field:
{
$group: {
"_id": "$username",
"count": {
$count: {}
}
}
},
{
$match: {
"count": {
$gte: 4
}
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
