我正在尝试在Mongodb中使用Spring数据中的聚合。经过几个阶段unwind
,lookup
,match
之后,我得出了跟随投影后数据的样本,然后尝试按_id
进行分组。
{ "_id": 1, "name":"Maths" },
{ "_id": 1, "name":"Maths" },
{ "_id": 2, "name":"Science" },
{ "_id": 2, "name":"Science" }
以下mongo脚本运行正常。
{
$project:
{
name: 1
}
},
{
$group:
{
_id: '$_id',
name: {
$first: '$name'
}
}
}
春天来的时候,
group("_id").first("name").as("name")
但显示错误Invalid reference '_id'!
但是当我执行以下操作时,它可以正常工作。
aggregationOperationContext -> {
return new Document("$group",
new Document("_id", "$_id").append("name", new Document("$first", "$name")));
}
为什么group()
不起作用?
Note:上面的代码是
的lamda expnew AggregationOperation() {
@Override
public Document toDocument(AggregationOperationContext aggregationOperationContext) {
// statements
}
}
实际上您的想法是正确的。投影时,只能像name
一样投影project("name")
,这样会得到_id
和name
。
但是在这种情况下,您还应该投影_id
字段。我认为您只投射了name
project("_id","name"),
group("_id").first("name").as("name")
这应该有效。我认为这可能是spring-data中的错误。