在 mongodb 中使用 findOne 获取具有最大 id 的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22118210/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 13:37:02  来源:igfitidea点击:

Using findOne in mongodb to get element with max id

mongodb

提问by Jorge

I am trying to retrieve one element from a mongo collection, the one with the greatest _id field. I know this can be done by querying:

我正在尝试从 mongo 集合中检索一个元素,即具有最大 _id 字段的元素。我知道这可以通过查询来完成:

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

But it kind of seems unelegant and I was wondering whether there is a way to get that specific element using findOne()

但这似乎有点不雅,我想知道是否有办法使用 findOne() 获取该特定元素

Note: I want to do this because, from what I've read in ObjectId, the first bytes correspond to the miliseconds since the Epoch and thus, the last element being inserted will have the greatest _id. Is there any other way to retrieve the last element inserted in a collection?

注意:我想这样做是因为,从我在ObjectId 中读取的内容来看,第一个字节对应于自 Epoch 以来的毫秒数,因此,插入的最后一个元素将具有最大的 _id。有没有其他方法可以检索插入集合中的最后一个元素?

回答by Asya Kamsky

You should use find, like you already are, and not aggregation which will be slower since it needs to scan allthe values of _id fields to figure out the max.

您应该使用find,就像您已经使用的那样,而不是聚合,因为它需要扫描_id 字段的所有值以找出最大值。

As comments pointed out there is nodifference between using find() and findOne() - functionally or elegance-wise. In fact, findOnein the shell (and in the drivers which implement it) is defined in terms of find (with limit -1 and with pretty print in the shell).

正如评论所指出的那样,使用 find() 和 findOne() 之间没有区别 - 无论是功能还是优雅。事实上,findOne在 shell 中(以及在实现它的驱动程序中)是根据 find 定义的(限制为 -1 并且在 shell 中具有漂亮的打印)。

If you reallywant to do the equivalent of

如果你真的想做相当于

db.collection.find().sort({_id:-1}).limit(1).pretty()

as findOneyou can do it with this syntax:

因为findOne您可以使用以下语法来做到这一点:

db.collection.findOne({$query:{},$orderby:{_id:-1}})

回答by Sumeet

You can get max _id using aggregation of mongodb. Find and sort may overkill's.

您可以使用 mongodb 的聚合获得 max _id。查找和排序可能会矫枉过正。

db.myCollection.aggregate({
    $group: {
        _id: '',
        last: {
            $max: "$_id"
        }
    }
});

回答by Albert s

with PHP driver (mongodb)
using findOne()

使用 PHP 驱动程序 (mongodb)
使用findOne()

$filter=[];
$options = ['sort' => ['_id' => -1]]; // -1 is for DESC
$result = $collection->findOne(filter, $options);
$maxAge = $result['age']

回答by nathaniel

import pymongo

tonystark = pymongo.MongoClient("mongodb://localhost:27017/")

mydb = tonystark["tonystark_db"]
savings = mydb["customers"]

x = savings.find().sort("_id")
for s in x:
    print(s)

回答by Gaurav Gauswami

$maxId="";

$Cursor =$collection->find();

foreach($cursor as $document) { 
    $maxid =max($arr=(array($document['id'])));
}

print_r($maxid+1);