MongoDB find get position of document after sort
Asked Answered
H

1

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)?

Haugh answered 4/7, 2017 at 19:23 Comment(4)
By "index" it looks like you are just referring to the position in the query results? If you Iterate the 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?Greaves
I need the position as rank. So each user know wich rank he has.Haugh
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.Greaves
Related question: Add some kind of row number to a mongodb aggregate command / pipeline. 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.Greaves
M
0

With MongoDB v5.0+, you can use $setWindowFields with $documentNumber to assign a field, say with the name position, to record the position of result set.

db.collection.aggregate([
  {
    "$setWindowFields": {
      "sortBy": {
        "created": -1
      },
      "output": {
        "position": {
          "$documentNumber": {}
        }
      }
    }
  }
])

Mongo Playground

Marquisette answered 4/10 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.