gpt4 book ai didi

java - MongoDb 使用聚合查询 Java 代码

转载 作者:行者123 更新时间:2023-12-02 10:55:50 24 4
gpt4 key购买 nike

有人可以帮我将下面的查询转换为java代码吗?

我已经用 java 编写了以下查询,如下所示,但出现以下错误,

命令失败,出现错误 168:“服务器上无法识别表达式 '$push'”。完整响应为 { "ok": 0.0, "errmsg": "无法识别的表达式 '$push'", "code": 168, "codeName": "InvalidPipelineOperator"}

查询:

db.getCollection('xyz').aggregate([
{$match: { "_id":{$in: [{"a" : "NA","b" : "HXYZ","c" : "12345","d" : "CA"}]}
}
},
{ $unwind: '$bal' },
{
$sort: {'bal.date': -1}
},
{$group:
{"_id": "$_id",bal:{$push:'$bal'}}},
{ $project: {
balances: { $slice: ["$bal",2]}
}
}

])

Java 代码:

List<Document> findDocument=collectionName.aggregate(
Arrays.asList(
Aggregates.match(in("_id",tempList)),
Aggregates.unwind("$bal"),
Aggregates.sort(Sorts.descending("bal.date")),
Aggregates.group(new Document("_id","$_id").append("bal",new Document("$push","$bal"))),
Aggregates.project(new Document("bal",new Document ("$slice",Arrays.asList("$bal", 2)))))).into(new ArrayList<Document>());

Mongo DB 版本为 3.4。有人可以告诉我为什么 $push 不起作用吗?提前致谢。

最佳答案

您正在将文档推送到 id 字段,而不是单独创建推送文档。

import static com.mongodb.client.model.Accumulators.*;
import static com.mongodb.client.model.Aggregates.*;
import static com.mongodb.client.model.Filters.in;
import static com.mongodb.client.model.Sorts.*;
import static java.util.Arrays.*;
List<Document> results = collectionName.aggregate(
asList(
match(in("_id",tempList)),
unwind("$bal"),
sort(descending("bal.date")),
group("$_id", push("bal","$bal")),
project(new Document("bal",new Document ("$slice", asList("$bal", 2))))
)
).into(new ArrayList<>());

关于java - MongoDb 使用聚合查询 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51761004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com