gpt4 book ai didi

java - 在 Mongo Java 驱动程序中过滤嵌套数组

转载 作者:行者123 更新时间:2023-11-30 07:06:38 25 4
gpt4 key购买 nike

以下 NoSQL 查询返回特定用户的所有评论:

db.getCollection('catalog-review').aggregate([
{
$project: {
reviews: {
$filter: {
input: "$reviews",
as: "review",
cond: { $eq: [ "$$review.userId", 121 ] }
}
}
}
}
])

此查询工作正常,但如果我使用 Mongo 驱动程序在 Java 中实现此查询,则“$$”不起作用。

List<CatalogReview> reviews = collection.aggregate(Arrays.asList(
new Document("$project", new Document("reviews", new Document("$filter", new Document("input", "$reviews")
.append("as", "review").append("cond", new Document("$eq", Arrays.asList(new Document("$$review.userId", 121)))))))
)).into(new ArrayList<>());

错误信息:

com.mongodb.MongoCommandException: Command failed with error 15999: 'invalid operator '$$review.userId'' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "invalid operator '$$review.userId'", "code" : 15999 }

Mongo驱动支持聚合函数吗?

最佳答案

问题是Arrays.asList(new Document("$$review.userId", 121))。它应该是Arrays.asList("$$review.userId", 121)

Arrays.asList(new Document("$$review.userId", 121)) = [ { "$$review.userId": 121 } ]

Arrays.asList("$$review.userId", 121) = [ "$$review.userId", 121]

代码片段应如下所示:

List<CatalogReview> reviews = collection.aggregate(Arrays.asList(
new Document("$project", new Document("reviews", new Document("$filter", new Document("input", "$reviews")
.append("as", "review").append("cond", new Document("$eq", Arrays.asList("$$review.userId", 121))))))
)).into(new ArrayList<>());

关于java - 在 Mongo Java 驱动程序中过滤嵌套数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40003410/

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