0

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().

2 Answers 2

1

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"));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot. With your solution I can even mix two approches
0

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"));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.