$lookup - Match from key inside array of objects in foreign collection

Hi,

How to perform a lookup from an array of objects in a foreign collection?

Example:

user collection:

{
  "uId": "user1"
}

Match Details Collection:

{
  "matchId": 123,
  "users": [
    {
      "uId": "user1",
      "session": "active",
    },
    {
      "uId": "user2",
      "session": "active",
    },
],
}

How do I perform a lookup on Match Details Collection where the users.uId is the link between these two collections without the use of the $unwind stage inside the pipeline parameter of the $lookup stage.

I tried using the $eq operator, but it didn’t work.

{
  "$lookup": {
    "from": "matchDetails",
    "let": {"userId": "$uId"},
    pipeline: [
      {
        "$match": {
          "$expr": {
            "$eq": ["$users.uId", "$$userId"],  // <-- This doesn't work. Dont want to use `$unwind` before `$match` stage
          },
        },
      },
    ],
  }
}
1 Like
db.users.aggregate([
  {
    $lookup:
      {
        from: 'matchDetails',
        localField: 'uId',
        foreignField: 'users.uId',
        as: 'details'
      }
  }
])

and this is the fix for your pipeline:

[{$lookup: {
    "from": "matchDetails",
    "let": {"userId": "$uId"},
    pipeline: [
      {
        "$match": {
          "$expr": {
            "$in": ["$$userId", "$users.uId"],  
          },
        },
      },
    ],
    as: "details"
  }}]

Notice that $users.uId is an array.

Goodluck,
Rafael,

2 Likes

Thanks a lot, @Rafael_Green

I taught $in will only work for arrays. But now I know that it will work even for an array of objects.

2 Likes

$users.uId is array of strings

1 Like

Is there any way to match inside an array of objects inside a pipeline?

I think it’s possible, my guess is that it’ll just compare the object to every object in the array of objects.

Post sample source documents and expected results.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.