mongodb 如何从 collections 中获取最大三个值
mongodb how to get max three value from collections
我有 mongodb collection 喜欢:
[{
"name": "a",
"price": 130
},
{
"name": "b",
"price": 90
},
{
"name": "c",
"price": 150
},
{
"name": "e",
"price": 170
},
{
"name": "g",
"price": 135
}]
我需要一个查询来从这个 collection 中获得最多三个“价格”。
db.collection.find().sort({price:-1}).limit(3)
查询
- 排序和限制为3的答案最简单
- 如果很多产品可以有相同的价格,也许前 3 个价格被超过 3 个产品共享,如果你想要所有这些产品你也可以使用这个,看例子,135 个价格由 2 个产品共享.
aggregate(
[{"$setWindowFields":
{"output": {"rank": {"$denseRank": {}}}, "sortBy": {"price": -1}}},
{"$match": {"$expr": {"$lt": ["$rank", 4]}}}, {"$unset": ["rank"]}])
升序排序,然后使用limit
db.collection.find({}).sort({ price: -1 }).limit(3);
我有 mongodb collection 喜欢:
[{
"name": "a",
"price": 130
},
{
"name": "b",
"price": 90
},
{
"name": "c",
"price": 150
},
{
"name": "e",
"price": 170
},
{
"name": "g",
"price": 135
}]
我需要一个查询来从这个 collection 中获得最多三个“价格”。
db.collection.find().sort({price:-1}).limit(3)
查询
- 排序和限制为3的答案最简单
- 如果很多产品可以有相同的价格,也许前 3 个价格被超过 3 个产品共享,如果你想要所有这些产品你也可以使用这个,看例子,135 个价格由 2 个产品共享.
aggregate(
[{"$setWindowFields":
{"output": {"rank": {"$denseRank": {}}}, "sortBy": {"price": -1}}},
{"$match": {"$expr": {"$lt": ["$rank", 4]}}}, {"$unset": ["rank"]}])
升序排序,然后使用limit
db.collection.find({}).sort({ price: -1 }).limit(3);