1

Using the aggregation framework I want to add the index of each element inside the array to the subdocument itself.

In a later stage I'd like to $unwind the elements, but then I need the old index inside the myResults Array.

Current structure:

{ myResults : [
    { foo: "bar"
    },
    { answer: 42
    }
]

Target structure:

{ myResults : [
    { index: 0,  // <-- this should be added
      foo: "bar"
    },
    { index: 1,  // <-- this should be added
      answer: 42
    }
]

Note: I don't want to update the elements, - I just want to use the index in a later stage of the aggregation pipeline.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133
d0x
  • 11,040
  • 17
  • 69
  • 104
  • 1
    +1 Interesting question. But judging by the fact that [these](http://stackoverflow.com/q/17640788/390819) [questions](http://stackoverflow.com/q/16191125/390819) are still not answered, I'd say it's not currently possible. – Cristian Lupascu Oct 24 '13 at 06:18

1 Answers1

3

You will want to vote up this issue in MongoDB Jira system:

Add option to $unwind to emit array index

It provides exact functionality that you are asking for. It is not currently scheduled for a particular future release, but that usually is influenced by how much it is needed. Adding a note to it explaining your use case and voting on it will influence its prioritization relative to other unscheduled aggregation framework tickets.

Asya Kamsky
  • 41,784
  • 5
  • 109
  • 133