I have MongoDB collection items with following documents:
{ "name": "First", "value": 8 },
{ "name": "Second", "value": 2 },
{ "name": "Third", "value": 5 }
I would like to sort them by name or value and then add sequence number (index property) to each of them (first item will have "index": 1, second "index": 2, etc.). So for this query:
db.items.aggregate([{ $sort: { "value": 1 } }])
result should be:
{ "name": "Second", "value": 2, "index": 1 },
{ "name": "Third", "value": 5, "index": 2 },
{ "name": "First", "value": 8, "index": 3 }
This should also works with $skip. With { "$skip": 1 }, result should be items with indexes 2, 3, not 1, 2. Is there any way to do this using pure MongoDB, without any application logic?