【问题标题】:get max _id in mongodb在mongodb中获取最大_id
【发布时间】:2020-04-20 18:33:12
【问题描述】:

我在 mongodb 中使用 nodejs 收集了这个集合:

_id:
name:
email:
date:

我想使用最大_id,我想要整数值。 我尝试了这段代码,但在找到最大值后我不知道如何使用。

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

我用 find 和 findone 尝试了很多代码,但我无法在 _id 中获得最大 int。 我不使用十六进制ID.. 我需要这个来创建具有未使用的 id 的新帐户,并且最后一个帐户是最大 _id。 有人有想法吗?

【问题讨论】:

    标签: mongodb max


    【解决方案1】:

    以下代码打印具有最大 _id 值的文档(在 mongo shell 中尝试过):

    var myCursor = db.test.find().sort( { _id: -1 } ).limit(1);
    
    if (myCursor.hasNext()) {
        let doc = myCursor.next();
        printjson(doc);
    }
    

    db.collection.find() 方法返回一个光标游标 有许多方法,您可以在其上应用并执行各种功能:Cursor Methods



    NodeJS 代码:
    db.test.find()
           .sort( [[ '_id', -1 ]] )
               .limit(1)
                  .toArray( (err, docs) => {
                       if (docs.length > 0) { 
                           let maxId = docs[0]._id;
                           console.log(maxId);
                       }
                       else { 
                           console.log('Nothing found!');
                       } );
    

    【讨论】:

    • 首先感谢您的帮助,但是当我在我的代码中编写此代码时,它显示 printjson undefind
    • printjson 是一个 mongo shell 命令。你在用什么编码?
    • 我在 node js 中使用 express 和 mongo db 模块编写
    • 那么,printjson 将无法在那里工作。在 NodeJS 代码(即 JS)中,你想用 max _id 值做什么?字段doc._id 将具有值-您可以console.log 并查看。
    • 使用 ._id 我无法获得对象的 _id,当我使用 findone 时我可以做到这一点,但 findone 不返回最大值。
    猜你喜欢
    • 2019-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 1970-01-01
    • 2015-01-02
    • 2016-03-26
    相关资源
    最近更新 更多