stackers
stackers

Reputation: 3299

How to use $lookup $let variables in mongodb?

Trying to do a lookup and use one of the variables but using $expr is confusing.

I'm pretty sure the let part is right, but it says to use it in the pipeline you need an $expr, but I don't understand where or what information to give it.

Here's what I have so far:

    {"$lookup": {
        "from": "likes",
        "let": {'content': "$_id"},
        "pipeline": [{'$match': { '$expr':  
            {user: mongoose.Types.ObjectId(req.user._id), content: mongoose.Types.ObjectId("$$content")}
           }}],
        "as": "liked"
    }},

Upvotes: 1

Views: 4768

Answers (1)

mickl
mickl

Reputation: 49985

You can only convert req.user._id using mongoose.Types.ObjectId as it becomes a constant value for Aggregation Framework. To convert a variable $$content you have to use $toObjectId operator.

{"$lookup": {
    "from": "likes",
    "let": {'content': "$_id" },
    "pipeline": [
        {'$match': { $expr: { $and: [ 
            { $eq: [ "$user", mongoose.Types.ObjectId(req.user._id) ] },
            { $eq: [ "$content", { $toObjectId: "$$content" } ] },
        ] } } }
    ],
    "as": "liked"
}},

Upvotes: 4

Related Questions