以下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/

10-09 05:46