Search code examples
javamongodbmongodb-queryspring-dataaggregation-framework

Spring Data Mongo Template - Counting an array


Mongo document:

{
    "_id" : "1",
    "array" : [
        {
            "item" : "item"
        }, 
        {
            "item" : "item"
        }
    ]
}

My mongo shell query looks like so:

db.getCollection('collectionName').aggregate(
    {$match: { _id: "1"}},
    {$project: { count: { $size:"$array" }}}
)

Is there anyway to implement this using the Mongo Template from Spring?

So far I have this:

MatchOperation match = new MatchOperation(Criteria.where("_id").is("1"));
ProjectionOperation project = new ProjectionOperation();
Aggregation aggregate = Aggregation.newAggregation(match, project);
mongoTemplate.aggregate(aggregate, collectionName, Integer.class);

I think I am only missing the project logic but I'm not sure if it is possible to do $size or equivalent here.


Solution

  • It's quite possible, the $size operator is supported (see DATAMONGO-979 and its implementation here). Your implementation could follow this example:

    import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;
    
    Aggregation agg = new Aggregation(
        match(where("_id").is("1")), //  
        project() //
            .and("array") //
            .size() //
            .as("count")
    );
    
    AggregationResults<IntegerCount> results = mongoTemplate.aggregate(
        agg, collectionName, Integer.class
    );
    List<IntegerCount> intCount = results.getMappedResults();