kertAW
kertAW

Reputation: 263

Pass data from one $lookup to another

There is an aggregate request that includes two $lookups:

[{
    $match: {
      id
    }
  },
  {
    $lookup: {      // 1
      from: 'blogs',
      as: 'blog',
      pipeline: [{
        $project: {
          id: 1,      // *           From this
          name: 1,
          articles: 1
        },
      }, {
        $match: {
          articles: {
            $in: [id]
          }
        }
      }, {
        $unset: 'articles'
      }]
    }
  },
  {
    $lookup: {      // 2
      from: 'users',
      as: 'user',
      pipeline: [{
        $project: {
          id: 1,
          user_name: 1,
          picture: 1
        },
      }, {
        $match: {
          blogs: {
            $in: [...]      // To this
          }
        }
      }]
    }
  }
]

How can you transfer a field from the first to the second (the field is marked with *)?

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Upvotes: 3

Views: 206

Answers (1)

Use let: { "blogIds": "$blog.id" }

and in pipeline use $$blogIds

$lookup: {
    from: 'users',
    as: 'user',
    let: { "blogIds": "$blog.id" }
    pipeline: [{ ... }]
}

Upvotes: 1

Related Questions