AJenkins AJenkins - 2 years ago 192
Java Question

Counting an array using Spring Data Mongo Template

Mongo document:

"_id" : "1",
"array" : [
"item" : "item"
"item" : "item"

mongo shell query
looks like so:

{$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
logic but I'm not sure if it is possible to do
$size or equivalent

Answer Source

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 = newAggregation(
    match(where("_id").is("1")), //  
    project() //
        .and("array") //
        .size() //

AggregationResults<IntegerCount> results = mongoTemplate.aggregate(
    agg, collectionName, Integer.class
List<IntegerCount> intCount = results.getMappedResults();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download