mongodb 如何从集合中获取最大值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32076382/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
mongodb how to get max value from collections
提问by Hossain Khademian
I have a mongodb collection like:
我有一个 mongodb 集合,如:
db.kids.find()
//results
[
{name:'tom', age:10},
{name:'alice', age:12},
....
]
I need a query to get MAX 'age' from this collection
like in SQL: SELECT MAX(age) FROM kids WHERE 1
我需要一个查询来从这个集合中获取 MAX 'age',就像在 SQL 中一样: SELECT MAX(age) FROM kids WHERE 1
回答by Hossain Khademian
db.collection.find().sort({age:-1}).limit(1) // for MAX
db.collection.find().sort({age:+1}).limit(1) // for MIN
it's completely usable but i'm not sure about performance
它完全可用,但我不确定性能
回答by popolvar
The performance of the suggested answer is fine. According to the MongoDB documentation:
建议答案的表现很好。根据MongoDB 文档:
When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n resultsas it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.
Changed in version 4.0.
当 $sort 紧跟在 $limit 之前时,优化器可以将 $limit 合并到 $sort 中。这允许排序操作在进行时只维护前 n 个结果,其中n 是指定的 limit,而 MongoDB 只需要在内存中存储 n 个项目。
在 4.0 版中更改。
So in the case of
所以在这种情况下
db.collection.find().sort({age:-1}).limit(1)
we get only the highest element WITHOUTsorting the collection because of the mentioned optimization.
由于提到的优化,我们只得到最高元素而不对集合进行排序。
回答by dier
what about using aggregate framework:
使用聚合框架怎么样:
db.collection.aggregate({ $group : { _id: null, max: { $max : "$age" }}});
回答by lvks2012
you can use group and max:
您可以使用组和最大值:
db.getCollection('kids').aggregate([
{
$group: {
_id: null,
maxQuantity: {$max: "$age"}
}
}
])
回答by Sumit S
Folks you can see what the optimizer is doing by running a plan. The generic format of looking into a plan is from the MongoDB documentation. i.e. Cursor.plan(). If you really want to dig deeper you can do a cursor.plan(true) for more details.
伙计们,您可以通过运行计划来查看优化器正在做什么。查看计划的通用格式来自 MongoDB文档。即 Cursor.plan()。如果你真的想深入挖掘,你可以做一个 cursor.plan(true) 以获得更多细节。
Having said that if you have an index, your db.col.find().sort({"field":-1}).limit(1) will read one index entry - even if the index is default ascending and you wanted the max entry and one value from the collection.
话虽如此,如果你有一个索引,你的 db.col.find().sort({"field":-1}).limit(1) 将读取一个索引条目 - 即使索引是默认升序并且你想要集合中的最大条目和一个值。
In other words the suggestions from @yogesh is correct.
换句话说,@yogesh 的建议是正确的。
Thanks - Sumit
谢谢 - 苏米特
回答by Hisham
db.collection.findOne().sort({age:-1}) //get Max without need for limit(1)
回答by Kankatala Krishna
For max value, we can write sql query as
对于最大值,我们可以将 sql 查询写为
select age from table_name order by age desc limit 1
same way we can write in mongodb too.
我们也可以用同样的方式在 mongodb 中编写。
db.getCollection('collection_name').find().sort({"age" : -1}).limit(1); //max age
db.getCollection('collection_name').find().sort({"age" : 1}).limit(1); //min age
回答by Shashwat Gupta
Simple Explanation, if you have mongo query Responsesomething like below - and you want only highest value from Array-> "Date"
简单解释,如果您有 mongo 查询 Response如下所示 - 并且您只想要Array-> "Date" 中的最高值
{
"_id": "57ee5a708e117c754915a2a2",
"TotalWishs": 3,
"Events": [
"57f805c866bf62f12edb8024"
],
"wish": [
"Cosmic Eldorado Mountain Bikes, 26-inch (Grey/White)",
"Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
"Suunto Digital Black Dial Unisex Watch - SS018734000"
],
"Date": [
"2017-02-13T00:00:00.000Z",
"2017-03-05T00:00:00.000Z"
],
"UserDetails": [
{
"createdAt": "2016-09-30T12:28:32.773Z",
"jeenesFriends": [
"57edf8a96ad8f6ff453a384a",
"57ee516c8e117c754915a26b",
"58a1644b6c91d2af783770b0",
"57ef4631b97d81824cf54795"
],
"userImage": "user_profile/Male.png",
"email": "[email protected]",
"fullName": "Roopak Kapoor"
}
],
},
***Then you have add
***然后你添加
Latest_Wish_CreatedDate: { $max: "$Date"},
Latex_Wish_CreatedDate: { $max: "$Date"},
somthing like below-
类似于下面的东西-
{
$project : { _id: 1,
TotalWishs : 1 ,
wish:1 ,
Events:1,
Wish_CreatedDate:1,
Latest_Wish_CreatedDate: { $max: "$Date"},
}
}
And Final Query Response will be below
最终查询响应将在下面
{
"_id": "57ee5a708e117c754915a2a2",
"TotalWishs": 3,
"Events": [
"57f805c866bf62f12edb8024"
],
"wish": [
"Cosmic Eldorado Mountain Bikes, 26-inch (Grey/White)",
"Asics Men's Gel-Nimbus 18 Black, Snow and Fiery Red Running Shoes - 10 UK/India (45 EU) (11 US)",
"Suunto Digital Black Dial Unisex Watch - SS018734000"
],
"Wish_CreatedDate": [
"2017-03-05T00:00:00.000Z",
"2017-02-13T00:00:00.000Z"
],
"UserDetails": [
{
"createdAt": "2016-09-30T12:28:32.773Z",
"jeenesFriends": [
"57edf8a96ad8f6ff453a384a",
"57ee516c8e117c754915a26b",
"58a1644b6c91d2af783770b0",
"57ef4631b97d81824cf54795"
],
"userImage": "user_profile/Male.png",
"email": "[email protected]",
"fullName": "Roopak Kapoor"
}
],
"Latest_Wish_CreatedDate": "2017-03-05T00:00:00.000Z"
},
回答by sunny prakash
You can also achieve this through aggregate pipeline.
您也可以通过聚合管道来实现这一点。
db.collection.aggregate([{$sort:{age:-1}}, {$limit:1}])