The first part works as expected and adds a field “lastDrIndex”: “b”.
The second part must not be the correct syntax, because it does not add anything to the results.
I would like the second part to take the value of lastDrIndex and use it to access the dataRequests.docs object at that position.
So in this example it would add a field
“lastDr”: { id: ‘b’, sampleValue: ‘two’ }
How do I fix the second part of the aggregate pipeline to use one field as an accessor to another object ?
Or can I somehow combine the two, since I don’t actually need the lastDrIndex and only need lastDr ?
First, you a typo in your first $addFields. Your field is dataRequests.id but you use dataRequests.ids.
Since docs is not an array, I am not too sure you could use the [ ] syntax. Even when I hard code the value b inside the 2nd $addFields it does not work.
I think you would need to use $objectToArray of dataRequests.docs with a $reduce to find the appropriate sampleValue. If this is a frequent use-case you might want to look at the attribute pattern. This would eliminate the need to use $objectToArray since your data will already be an array.
I did notice my typo, but I cannot edit the post.
Unfortunately, I cannot feasibly change the way the data is stored.
I would normally choose to use a much more standard practice like you suggested, or normalize the data into other collections.
I can look at the ObjectToArray and reduce functions, thank you.