如何在Spring MongoDB聚合中写入单个子ID字段
问题描述:
我正在尝试从Spring Data Mongo Aggregation获得以下查询:
I am trying to get following query from Spring Data Mongo Aggregation:
{
"_id": {
"year": "$_id.year"
},
"result": {
"$push": {
"rs": "$_id.rs",
"vl": "$vl"
}
}
}
我尝试了以下操作:
GroupAggregation as = group( "_id.year" ).push( new BasicDBObject( "rs", "$_id.rs" ).append( "vl", "$vl" ) ).as( "result" );
但是它会生成此表达式,其中"_id"字段下没有子字段"year":
But it generates this expression where there is no sub field "year" under "_id" field:
{ "$group" : { "_id" : "$_id.year" , "result" : { "$push" : { "rs" : "$_id.rs" , "vl" : "$vl"}}}}
关于如何使用spring数据mongodb聚合获取该查询的任何想法?
Any ideas on how to get that query using spring data mongodb aggregation?
答
我看不到api中的任何钩子来访问先前的 _id
值.
I don't see any hook in the api to access the previous _id
value.
您可以使用 AggregationOperation
使用mongodb类型创建 $ group
阶段.
You can use AggregationOperation
to create $group
stage using mongodb types.
类似
AggregationOperation group = new AggregationOperation() {
@Override
public DBObject toDBObject(AggregationOperationContext aggregationOperationContext) {
return new BasicDBObject("$group", new BasicDBObject("_id", new BasicDBObject("year", "$_id.year" )).append("result", new BasicDBObject("$push", new BasicDBObject( "rs", "$_id.rs" ).append( "vl", "$vl" ))));
}
};