skip to Main Content

I have mongodb collection like:

[{
    "name": "a",
    "price": 130
},
{
    "name": "b",
    "price": 90
},
{
    "name": "c",
    "price": 150
},
{
    "name": "e",
    "price": 170
},
{
    "name": "g",
    "price": 135
}]

I need a query to get max three "price" from this collection.

3

Answers


  1. db.collection.find().sort({price:-1}).limit(3)

    Login or Signup to reply.
  2. Query

    • the answer with the sort and limit 3, is the simplest
    • if many products can have the same price, maybe the 3 top prices is shared by more than 3 products, if you want all those products you can use this also, see the example, 135 price is shared from 2 products.

    Playmongo

    aggregate(
    [{"$setWindowFields": 
       {"output": {"rank": {"$denseRank": {}}}, "sortBy": {"price": -1}}},
     {"$match": {"$expr": {"$lt": ["$rank", 4]}}}, {"$unset": ["rank"]}])
    
    Login or Signup to reply.
  3. Use .sort() and .limit() for that

    sort in ascending order and then use limit

    db.collection.find({}).sort({ price: -1 }).limit(3);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search