lukaszrys
lukaszrys

Reputation: 1786

MongoDB aggregation Spring/Java (project with array, group and match)

I'm having trouble to write that query in Java using springframework.

db.getCollection('fish').aggregate(
        {$match : {"uploadDate" : { $gte : new ISODate("2017-05-22T00:00:00Z"), $lte : new ISODate("2017-05-25T00:00:00Z") }}},
        {$group: {_id: {lake : "$lake", type : "$type"}, count: {$sum: 1}}} ,
        {$project: {array : ["$_id.type" , "$count"], count : "$count"}},
        {$group: {_id: {lake : "$_id.lake"}, count: {$sum: 1}, types : {$addToSet : "$array"}}})

I was able to write match and group but I'm having trouble to add project that has array containing both id.type and count. So far I was able to write this

Aggregation aggregation = newAggregation(match(Criteria.where("uploadDate").gte(created).lte(newCreatedDate)),
        group("lake").count().as("values"));

I couldn't find any solution how to write it and I only see that you can add Fields/Strings to project().

Upvotes: 0

Views: 941

Answers (2)

letsDoThis
letsDoThis

Reputation: 71

I agree with the solution given by user2683814 but not sure solution was not working. But by using org.bson.Document instead of BasicDBObject fixed the issue, so thought to share.

AggregationOperation project = aggregationOperationContext -> new Document("$project", new Document("array", Arrays.asList("$_id.type" , "$count")).append("count", "$count"));

Upvotes: 0

s7vr
s7vr

Reputation: 75914

I'll give you the alternative as there is really no way to create the expressions the way you want.

You have to use AggregationOperation and use BasicDBObject to create the project stage.

Something like

AggregationOperation project = aggregationOperationContext -> new BasicDBObject("$project", new BasicDBObject("array", Arrays.asList("$_id.type" , "$count")).append("count", "$count"));

Upvotes: 1

Related Questions