0

I have some documents like this:

{
  "user": '1'
},
{ "user": '1'
},
{
  "user": '2'
},
{
  "user": '3'
}

I'd like to be able to get a set of all the different users and their respective counts, sorted in decreasing order. So my output would be something like this:

{
  '1': 2,
  '2': 1,
  '3': 1
}

So, in mongodb is :

db.collection.aggregate(
   {$group : { _id : '$user', count : {$sum : 1}}}
).result

But I want to do this in java. I tried this:

AggregateIterable it = collection.aggregate(Arrays.asList(
        group("$id", Accumulators.sum("$user", 1)),
        sort(Sorts.descending("$user"))
));

But it's wrong... How I can do this?

1 Answer 1

2

Try this:

AggregateIterable it = collection.aggregate(Arrays.asList(
    group("$user", Accumulators.sum("count", 1)),
    sort(Sorts.descending("count"))
));
Sign up to request clarification or add additional context in comments.

2 Comments

thanks!, how can I do if I want to show another field of the document?
You can calculate another field as part of a group like this: group("$customerId", sum("totalQuantity", "$quantity"), avg("averageQuantity", "$quantity")), however, if you want fields from the original document to come up, try using facet.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.