Access custom variable created in nested maps

Hi, is it possible to access variables created in $map as such:

...
$map: {
  input: "$x",
  as: "map1",
  in: {
    key1: "$$map1.somevalue",
    mapper: {
      $map: {
        input: "$y",
        as: "map2",
        in: { key2: "$$key1" // access key from above }
      }
    }
  }
}

something similar in JS:

[1,2,3,4,5].map(ele => ({ 
  a: ele, 
  b: new Array(ele).fill(0).map(item => ({ c: a })) // doesn't work here like this
}))

Hi @Sambhav_Jain3,

Have you attempted using $let?

I have the following sample documents:

[
  { x: [ 1, 2, 3, 4, 5 ] },
  { x: [ 1, 2, 3, 4, 5 ], y: [ 10, 20, 30, 40, 50 ] }
]

Example aggregation with $let and the output:

var b = 
{
  '$addFields': {
    test: {
      '$map': {
        input: '$x',
        as: 'map1',
        in: {
          '$let': {
            vars: { key1: '$$map1' },
            in: {
              mapper: {
                '$map': { input: '$y', as: 'map2', in: { key2: '$$key1' } }
              }
            }
          }
        }
      }
    }
  }
}
db.array.aggregate(b)
[
  {
    _id: ObjectId("646433adc39a2fadd17b3963"),
    x: [ 1, 2, 3, 4, 5 ],
    test: [
      { mapper: null },
      { mapper: null },
      { mapper: null },
      { mapper: null },
      { mapper: null }
    ]
  },
  {
    _id: ObjectId("64643544c39a2fadd17b3964"),
    x: [ 1, 2, 3, 4, 5 ],
    y: [ 10, 20, 30, 40, 50 ],
    test: [
      {
        mapper: [
          { key2: 1 },
          { key2: 1 },
          { key2: 1 },
          { key2: 1 },
          { key2: 1 }
        ]
      },
      {
        mapper: [
          { key2: 2 },
          { key2: 2 },
          { key2: 2 },
          { key2: 2 },
          { key2: 2 }
        ]
      },
      {
        mapper: [
          { key2: 3 },
          { key2: 3 },
          { key2: 3 },
          { key2: 3 },
          { key2: 3 }
        ]
      },
      {
        mapper: [
          { key2: 4 },
          { key2: 4 },
          { key2: 4 },
          { key2: 4 },
          { key2: 4 }
        ]
      },
      {
        mapper: [
          { key2: 5 },
          { key2: 5 },
          { key2: 5 },
          { key2: 5 },
          { key2: 5 }
        ]
      }
    ]
  }
]

The above demonstration is just an example of using $let - I do not know what your expected output is or what your document structure is like. Hopefully use of $let works for your environment / use case.

Regards,
Jason