简体   繁体   English

Spring Data等效于聚合查询

[英]Spring Data equivalent of aggregation query

I'm having hard time figuring out how to write spring data implementation for the below aggregation query. 我很难弄清楚如何为下面的聚合查询编写spring数据实现。 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. 我知道.push()的参数必须固定,但我不知道如何。 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: 如果要向$push提供BasicDBObject,请使用.append方法添加其他字段:

    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. 另请注意,在使用“类型化”输出时,您使用的类类型必须与“输出”的结构相匹配,而不是与正在使用的“输入”类的结构相匹配,因为它们当然会有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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