简体   繁体   中英

Spring Data equivalent of aggregation query

I'm having hard time figuring out how to write spring data implementation for the below aggregation query. Some background of my problem can be found here

db.asset.aggregate([{$unwind:"$folderIds"},  {$group:{_id: "$folderIds",assets:{$push: {assets_id:"$_id",display_name:"$displayName"}}}}])

I have got the below piece of code so far

AggregationOperation unwind = Aggregation.unwind("folderIds");
AggregationOperation groupFolderIds = Aggregation.group("folderIds")
            .push(new BasicDBObject().put("assetId", "$_id")).as("assets");
Aggregation aggregation = Aggregation.newAggregation(unwind, groupFolderIds);
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, "asset", Map.class);

I know the argument to .push() has to be fixed but I don't know how. I would like to extract a few fields from the asset document in the result. Help is appreciated. Thank you.

If you are supplying a BasicDBObject to $push then use the .append method to add additional fields:

    Aggregation aggregation = newAggregation(
            unwind("folderIds"),
            group("folderIds")
                .push(
                    new BasicDBObject("assets_id","$_id")
                     .append("display_name","$displayName")
                ).as("assets")
    );

Also note when using "typed" output, the class type you use must match the structure of the "output" and not the "input" class that is being used as they will of course be different.

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