1

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?

1

2 Answers 2

1

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} }
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.