简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM