user14901756
user14901756

Reputation:

Mongoose get position of a data

I'm using this code to get my user leaderboard

var data = await db.models.user
    .find({ points: { $ne: 0 } })
    .collation({locale: "en_US", numericOrdering: true})
    .sort('-points')
    .limit(10)
    .skip(page*10-10)

But I can't find how to get users position in the all leaderboard. How can I get it?

Upvotes: 2

Views: 435

Answers (1)

turivishal
turivishal

Reputation: 36114

I don't think there is any good approach or method to do this, but you still want to do it then try using aggregate() and $unwind stage,

  • $match your conditions
  • $sort by points in descending order
  • $group by null and make array of all documents in docs
  • $unwind deconstruct docs array and pass includeArrayIndex: 'position' this will create a ordered index field position in each document, starting from zero(0),
  • $skip and $limit stages
var data = await db.models.user.aggregate([
  { $match: { points: { $ne: 0 } } },
  { $sort: { points: -1 } },
  {
    $group: {
      _id: null,
      docs: { $push: "$$ROOT" }
    }
  },
  {
    $unwind: {
      path: "$docs",
      includeArrayIndex: "position"
    }
  },
  { $skip: 10 },
  { $limit: page*10-10 }
])

Playground

This may heavy operation, might be take more execution time in big data!

Upvotes: 1

Related Questions