2
votes

If I sort the results of an aggregation query can I access the documents position in the results? This would be used to perform a calculation inside $project instead of returning the results and iterating over them.

The desired outcome where document position would be 0, 1, 2 etc:

db.trips.aggregate([
  { $match: { driver: "xx" } },
  { $sort: {  "start.time": -1 } },
  { $project: {
     _id: 1,
     driver: 1
     document_position: ____ 
  } }
])
1
I don't think you can do exactly what you want. Could you describe instead what the end goal is? Maybe there is another path to the final goal. - wdberkeley

1 Answers

0
votes

What you need is the $limit and $skip pipeline stages. Using them you can only obtain a sequence of records and not be able to pick records from indices which are not contiguous.

var fromindex = 1;  // define the index from which you want to pick the documents.
                    // Assuming index starts from 0.
var numberOfDocuments = 3; // The number of documents from the position.

db.trips.aggregate([
{$match:{"driver": "xx"}},
{$sort:{"start.time": -1}},
{$skip:fromindex-1},
{$limit:numberOfDocuments},
{ $project: {
     _id: 1,
     driver: 1
}
])

This would return the documents in position 1,2,3 in sorted order.

If you see, the $project stage does not have the document position in it. It is not required, since you would get the result in order and could convert it to an array and obtain the documents by the index on the client side.