问题
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