Home > Back-end >  mongodb how to get max three value from collections
mongodb how to get max three value from collections

Time:05-01

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.

CodePudding user response:

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

CodePudding user response:

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"]}])

CodePudding user response:

Use .sort() and .limit() for that

sort in ascending order and then use limit

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