按ID分组在Spring数据mongodb中不起作用

问题描述 投票:0回答:1

我正在尝试在Mongodb中使用Spring数据中的聚合。经过几个阶段unwindlookupmatch之后,我得出了跟随投影后数据的样本,然后尝试按_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 exp
new AggregationOperation() {
    @Override
    public Document toDocument(AggregationOperationContext aggregationOperationContext) {
        // statements
    }
}
spring mongodb spring-boot aggregation-framework spring-data-mongodb
1个回答
1
投票

实际上您的想法是正确的。投影时,只能像name一样投影project("name"),这样会得到_idname

但是在这种情况下,您还应该投影_id字段。我认为您只投射了name

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

这应该有效。我认为这可能是spring-data中的错误。

© www.soinside.com 2019 - 2024. All rights reserved.