7

Is it possible to get the position of a document for a query? Example:

db.users.find().sort({created:-1})

returns:

0: {name:"user1",created:5}
1: {name:"user1",created:4}
2: {name:"user1",created:3}
3: {name:"user1",created:2}

How to get these indexes (0,1,2,3)?

Stennie
  • 63,885
  • 14
  • 149
  • 175
neoexpert
  • 465
  • 1
  • 10
  • 20
  • 2
    By "index" it looks like you are just referring to the position in the query results? If you [Iterate the cursor](https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/) returned by a query you can store a variable with the current loop iteration and print this out along with the result. Is there some other processing you'd like to do with this value? – Stennie Jul 05 '17 at 03:59
  • I need the position as rank. So each user know wich rank he has. – neoexpert Jul 05 '17 at 06:27
  • 1
    As per my previous comment, I would add the position when you iterate the results to return or display to your end user. As at MongoDB 3.4 there is no in-built server feature to explicitly number query results, but you can easily handle this in your application/display logic. It's possible (but not overly efficient) to calculate row numbers using the aggregation framework. If you're having trouble figuring out how to display the rank I would edit your question or post a new one including details of how you are returning results to the end user and code examples for what you've tried. – Stennie Jul 09 '17 at 01:04
  • Related question: [Add some kind of row number to a mongodb aggregate command / pipeline](https://stackoverflow.com/q/35174554/1388319). I wouldn't recommend this approach for common queries or those with a large number of results, but the possibility exists if you aren't concerned about efficiency or scalability. – Stennie Jul 09 '17 at 01:11

0 Answers0