ASHafizullah
ASHafizullah

Reputation: 729

How to get ranking from point in mongodb?

i have a problem with how to get ranking from mongodb? I have a data in "cvanalyze" collection like this:

{
    "_id": "123"
    "user": "name 1",
    "point": 208,
},
{
    "_id": "124"
    "user": "name 2",
    "point": 215,
}
{
    "_id": "125"
    "user": "name 3",
    "point": 185,
}

And when i get data from user ID: 124, i want to get result json like this: Because user id 124 points is greatest value.

{
    "_id": "124"
    "user": "name 2",
    "point": 215,
    "rank": 1 //SHOW RANK HERE
}

How to make a code with mongodb aggregration for get result like that? Thanks before.

Upvotes: 1

Views: 334

Answers (1)

Gibbs
Gibbs

Reputation: 22974

I have edited my entire answer to an easy approach.

playground

db.collection.aggregate([
  {
    $sort: {//Descending sort
      point: -1
    }
  },
  {//Get 1
    "$limit": 1
  },
  {//Add the required field 
    "$addFields": {
      rank: 1
    }
  }
])

Edit:

Updated play

db.collection.aggregate([
  {
    $sort: {
      point: -1
    }
  },
  {
    $group: {//Add in an array
      "_id": null,
      "items": {
        "$push": "$$ROOT"
      }
    }
  },
  {
    "$unwind": {//De-normalize and get index
      "path": "$items",
      "includeArrayIndex": "items.rank"
    }
  },
  {
    "$replaceRoot": {//Reshape
      "newRoot": "$items"
    }
  },
  {
    "$addFields": {//Add 1 to get to proper rank as array is index starts 0
      "newRank": {
        "$add": [
          "$rank",
          1
        ]
      }
    }
  }
])

Edit:

It's all about placing the pipeline. Data flows one by one pipeline.

Updated play

You need to add match stage at last.

Upvotes: 2

Related Questions