Group by id doesn't work in spring data mongodb

百般思念 提交于 2020-05-17 06:08:06

问题


Im trying to use Aggregation in Spring data with mongodb. After few stages unwind, lookup, match I come up with the sample following data which is after the projection, then I try to group it by _id.

{ "_id": 1, "name":"Maths" },
{ "_id": 1, "name":"Maths" },
{ "_id": 2, "name":"Science" },
{ "_id": 2, "name":"Science" }

The following mongo script is working perfectly.

{
    $project: 
    {
        name: 1
    }
}, 
{
    $group: 
    {
        _id: '$_id',
        name: {
            $first: '$name'
        }
    }
}

When I do it in spring,

group("_id").first("name").as("name")

But it shows an error Invalid reference '_id'! But when I do something like following, its working fine.

aggregationOperationContext -> {
  return new Document("$group",
             new Document("_id", "$_id").append("name", new Document("$first", "$name")));
}

Why doesn't group() work?

Note : The above code is lamda exp of

new AggregationOperation() {
    @Override
    public Document toDocument(AggregationOperationContext aggregationOperationContext) {
        // statements
    }
}

回答1:


Actually the way you think is correct. When you project you just can project name only like project("name") which gives _id and name as result.

But in this case you should project the _id field also. I think you projected only name

project("_id","name"),
group("_id").first("name").as("name")

This should work. I think it might be a bug in spring-data.



来源:https://stackoverflow.com/questions/61745356/group-by-id-doesnt-work-in-spring-data-mongodb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!