我在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
}
]我该怎么办?
感谢您的建议
发布于 2021-05-23 19:04:34
MongoDB $group运算符不允许筛选(仅限accumulator operators)。
你的第二个代码尝试这样做:
{
$group:{
_id:null,
test1:{
$push:"$test1"
},
test2:{
$push:"$test2"
},
...
}
}你得到的结果是错误的
解决方案:分组前的过滤器(MongoPlayground)
MatchOperation match = Aggregation.match(Criteria.where("name").in(Arrays.asList(params)))
GroupOperation group = Aggregation.group().push("name").as("name");发布于 2021-05-25 11:22:37
我应该使用下面的代码
group = group.push(params[i]).as(params[i]);https://stackoverflow.com/questions/67648349
复制相似问题