Syntax for $lookup let with List<Variable>

List<Variable> let = new ArrayList<>();
    Variable variable = new Variable("id", "$_id");
    Bson lookup = Aggregates.lookup("comments", let, lookUpPipeline, "comments");

I m just guessing how to do the following syntax, but I can’t find a proper example of this… any hints?

Figured out you need to declare Type of the Variable<> … not there yet though…seems I cant seem to find any comments yet… might be some faulty match value…

Aggregates.match(eq("$movie_id", “$$id”));

results in the following error:
com.mongodb.MongoCommandException: Command failed with error 2 (BadValue): ‘unknown top level operator: $movie_id’ on server The full response is { “operationTime” : { “$timestamp” : { “t” : 1551132725, “i” : 1 } }, “ok” : 0.0, “errmsg” : “unknown top level operator: $movie_id”, “code” : 2, “codeName” : “BadValue”, “$clusterTime” : { “clusterTime” : { “$timestamp” : { “t” : 1551132725, “i” : 1 } }, “signature” : { “hash” : { “$binary” : “Fj21OaPqB9QT4UlOL0GYDRiOruI=”, “$type” : “00” }, “keyId” : { “$numberLong” : “6658321991776337921” } } } }

…I really like the Builders, but for this one…-_-

Any helps about this subject ?

Bson lookup = Aggregates.lookup(“comments”, let, aPipeline, “comments”);

I need to write in Java the let variable.

Compass gives me the value of these variables:

new Document(“id”, “_id”)

ArrayList<Variable<Object>> let = new ArrayList<Variable<Object>>();

Create a new ArrayList<Variable> and add the $_id variable from the movie source collection to it.

    List<Variable<String>> let = new ArrayList<>();
    let.add(new Variable("movieId", "$_id"));

It’s a pity that Compass could extract the java code from the aggregation pipeline. (at least in my case)


perfect. it works. Thanks for your help.

any idea, how to sort using Aggregates.lookup() method ?

Hi TMJ18,
I personnally used a $sort operator in the pipeline attribute of lookup. For example, I used this block to sort comments by descending date.

lookup : { from: 'comments', let: {'mid' : '_id’},
{’$match’ : {’$expr’: {’$eq’: [’$movie_id’, ‘$$mid’]}}},
{ ‘$sort’ : {‘date’: -1}}
as: ‘movie_comments’


combination Filters.expr(Filters.eq(…)) does not work…
Using as much builders as possible I found nothing better for now then the following:

    Bson expr = Filters.expr(new Document("$eq", Arrays.asList("$movie_id", "$$id")));
    Bson matchLetId = Aggregates.match(expr);

Hi @SvenDhaens,

Have you tried using Compass Aggregation builder Export to Language ?


I did but it doesnt work if you tick the option with builders.

I was persistent in using builders, but I lost a lot of time for this.

It would be nice to see some kind of Builder for this case. Although I got it working now.