9

spring-data-mongodb 聚合问题

 3 years ago
source link: https://www.v2ex.com/t/778560
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

V2EX  ›  MongoDB

spring-data-mongodb 聚合问题

  anthoy · 1 天前 · 313 次点击

我在 spring-data-mongodb 中使用聚合,目的是实现查询下面数据

{
    "name":"test1",
    "receivedDate":"2021-05-18 00:00:52",
}
{
    "name":"test2",
    "receivedDate":"2021-05-18 00:00:52",
}
{
    "name":"test3",
    "receivedDate":"2021-05-18 00:00:52",
}
{
    "name":"test4",
    "receivedDate":"2021-05-18 00:00:52",
}

目标是通过聚合查询出来结果如下:

{
	"name":["test1","test2","test3","test4"],
}

目前使用方式是这样子

GroupOperation group = Aggregation.group().push("name").as("name");
[
    {
        "_id": null,
        "name": [
            "test1",
            "test2",
            "test3",
            "test4",
            "test4"
        ]
    }
]

但我修改为使用动态添加的时候

        GroupOperation group = Aggregation.group();
        for (int i = 0; i < params.length; i++) {
            group.push(params[i]).as(params[i]);
        }

发现查询的结果为

[
    {
        "_id": null
    }
]

感觉动态 push 哪里并没有生效,查询了挺多的资料好像也没有找到,感觉使用人挺少的

  • 有没有大佬知道应该怎么写的?
  • 或者还有别的方式实现
  • 或者自己遍历会不会比使用聚合这个更加好?

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK