2

Following NoSQL query returns all reviews of a particular user :

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

This is query works fine but if I implement this in Java using Mongo driver, the "$$" doesn't work.

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

The error message:

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 }

Does Mongo driver supports aggregate functions ?

1 Answer 1

3

The problem is Arrays.asList(new Document("$$review.userId", 121)). It should be Arrays.asList("$$review.userId", 121).

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

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

The snippet should be like below:

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<>());
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm ! Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.