In mysql, I have a query like:
mysql> SELECT user_id, count(user_id) as dup FROM addressbook GROUP BY user_id HAVING dup>20 ORDER BY dup;
You can directly get the number of elements in the addressBook
array field of each user by using $size:
db.users.aggregate([
{$project: {_id: 1, count: {$size: '$addressBook'}}}
])
Output:
{
"result" : [
{
"_id" : ObjectId("540c83f9d901f28b921a328c"),
"count" : 2
}
],
"ok" : 1
}
Note that the $size
operator was introduced in MongodB 2.6.
Your id condition is blank and you do not have a where clause. I think this would be more like your sql query. Note that in case you have user_id in your users collection then you should replace $_id with $user_id
db.users.aggregate( [
{ $match: { dub: { $gt: 20 } } },
{
$group: {
_id: "$_id",
count: { $sum: 1 }
}
}
])