shemerk
shemerk

Reputation: 387

Mongo: How to count aggregation groups via Java's MongoTemplate

I have the following data:

{groupId: 1, name: Jon},
{groupId: 1, name: Dan},
{groupId: 2, name: Jon},
{groupId: 2, name: Ris},
{groupId: 3, name: David}

I recieve as an input an array of groupID's, and I want to count the amount of DISTICT names in total for those groups, I defined the aggregation code as follows:

    groupIds [] = {1,2}

   Aggregation agg = newAggregation(
            match(Criteria.where("groupId").in((groupIds)),
            group("name").count().as("total")
    );

but I get a groupResult containing a count for each name, i.e.:

{name : Jon, total : 2}
{name : Dan, total : 1}
{name: Ris, total : 1}

while I actually want to get the total count which is = 3 (which is actually the size of the above groupResult)

how do I need to adjust my aggregation to accomplish that?

Thanks!

p.s. David is ignored from the count - as intended

Upvotes: 4

Views: 7109

Answers (1)

chridam
chridam

Reputation: 103475

To get the size of the last group, you can introduce another final $group pipeline stage where you can use a null group by key to group all the documents and then compute the accumulated sum.

In mongo shell, this would translate to

db.collection.aggregate([
   { "$match": { "groupId": { "$in": [1, 2] } } },
   {
       "$group": {
           "_id": "$name"               
       }
   },
   {
       "$group": {
           "_id": null,
           "total": { "$sum": 1 }
       }
   }
])

With Spring Data, this should follow:

Aggregation agg = newAggregation(
    match(Criteria.where("groupId").in((groupIds)),
    group("name"),
    group().count().as("total")
);

Upvotes: 2

Related Questions