按ID分组在Spring Data MongoDB中不起作用 [英] Group by id doesn't work in spring data mongodb

查看:252
本文介绍了按ID分组在Spring Data MongoDB中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在Mongodb中使用Spring数据中的聚合。经过几个阶段展开查找匹配并在投影后得到以下样本数据,然后尝试按 _id 分组。

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" }

以下mongo脚本运行良好。

The following mongo script is working perfectly.

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

在春季时,

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

但显示错误引用'_id'无效!
但是,当我执行以下操作时,它的工作正常。

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")));
}

为什么不 group()工作吗?

注意:上面的代码是

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


推荐答案

实际上,您认为正确的方式。当您进行投影时,仅可以投影 name ,就像 project( name)一样,给出 _id name 作为结果。

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.

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

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")

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

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

这篇关于按ID分组在Spring Data MongoDB中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆