Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-71428

Expose the array index in a $map operation

    • Type: Icon: Improvement Improvement
    • Resolution: Unresolved
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Aggregation Framework
    • Labels:
    • Query Optimization

      Currently the only way to know the element index in a $map is to create a "for loop" using $range:

      {$map: {
        input: {$range: [0, {$size: "$arr"}]},
        as: "x",
        in: {index: "$x", value: {$arrayElemAt: ["$arr", "$$x"]}}
      

       
      A simpler and more understandable option would be to have a meta variable such as $$index which is automatically set to the current array index. If would have no impact on existing aggregation pipelines but would simplify situations where the array index is needed, changing the example above to:

      {$map: {input "$arr", as "x", in: {index: "$$index", value "$$x"}}}
      

            Assignee:
            backlog-query-optimization [DO NOT USE] Backlog - Query Optimization
            Reporter:
            peter.williamson@mongodb.com Peter Williamson
            Votes:
            1 Vote for this issue
            Watchers:
            13 Start watching this issue

              Created:
              Updated: