Home > other >  MongoDb query to retrieve top 10 scores
MongoDb query to retrieve top 10 scores

Time:12-14

I have the data on my mongodb like this,

[{
    name: "user1",
    image: "image",
    score: 10
  },
  {
    name: "user2",
    image: "image",
    score: 167
  },
  {
    name: "user3",
    image: "image",
    score: 1
  },
  {
    name: "user4",
    image: "image",
    score: 102
  },
  {
    name: "user5",
    image: "image",
    score: 12
  }
]

I would like to retrieve the top 10 scores in descending order. Can someone help me out with the query for the same. Any help would be greatly appreciated.

CodePudding user response:

Something like this

explained: You can do with find() or aggregate() using the two stages sort limit

Option 1 - find:

 db.collection.find({}).sort({score:-1}).limit(10)

Option 2 - aggregate:

db.collection.aggregate([
   {
     $sort: {
       score: -1
     }
   },
   {
     $limit: 10
   }
 ])

CodePudding user response:

You can use sort() and limit() methods from MongoDB but notice that:

If using limit() with sort(), be sure to include at least one field in your sort that contains unique values, before passing results to limit().

 db.collections.find().sort( { score: -1 } ).limit(10)
  • Related