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

时间:2016-10-12 16:12:58

标签: java mongodb

在NoSQL查询之后返回特定用户的所有评论:

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<>());

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

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 }

错误消息:

WebDriver.Navigate().GoToUrl(urlthatredirectstohttps); 

Mongo驱动程序是否支持聚合函数?

1 个答案:

答案 0 :(得分:1)

问题是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<>());