AppreciateIt
AppreciateIt

Reputation: 706

MongoDB Aggregate - Count objects of a specific matching field

I want to know how to use aggregate() to take all of the objects of a specific field (i.e. "user") and count them.

This what I am doing:

I want to return a list of users with the sum of how many tweets that have made?

So I want output that looks like

Etc..

Also I don't want repeating users like

Etc..

which is what the above aggregate does.

So basically, how can I modify this aggregate to ensure the objects are unique?

Upvotes: 1

Views: 679

Answers (2)

krishna Prasad
krishna Prasad

Reputation: 3812

If you want whole inner user object in each documents after aggregation then you have to use $push operator in aggregation and also you need to do the aggregation on unique id of users e.g: id or id_str instead of $user object as in your question.

db.tweets.aggregate([{ $group: {_id: "$user.id", totalTweets: { $sum: 1 }, user : { $push: "$user" }  }    }])

This will solved your problem. For details about $push operator, have a look at official documents $push

Upvotes: 0

AdamExchange
AdamExchange

Reputation: 1299

I believe you will want to group by the user.id field instead of the user object. You can try doing that directly

$group: {_id: "$user.id", totalTweets: {$sum: 1} }

Or you might want to try projecting that field onto the document before grouping

$addFields: {userId: "$user.id"}
$group: {_id: "$userId", totalTweets: {$sum: 1} }

Upvotes: 1

Related Questions