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.

1
  • 1
    +1 Interesting question. But judging by the fact that these questions are still not answered, I'd say it's not currently possible. Commented Oct 24, 2013 at 6:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.