【问题标题】:Is there a findById shortcut for the MongoDB shell?MongoDB shell 是否有 findById 快捷方式?
【发布时间】:2015-10-04 20:00:34
【问题描述】:

我在 mongo DB shell 中最常做的事情是通过 ID 查找对象,例如:

db.collection.find({_id: ObjectId("55a3e051dc75954f0f37c2f2"})

我一遍又一遍地这样做,我发现必须一遍又一遍地用 ObjectId 包装 id 变得陈旧。我希望我有一个类似 findById 的简写形式,就像猫鼬提供的一样。我觉得 shell 应该足够聪明,可以理解我在这里的意思,例如:

db.collection.find("55a3e051dc75954f0f37c2f2")

我该怎么做?或者在 mongo shell 中有没有其他的通过 id 查询的方法?

【问题讨论】:

    标签: mongodb mongodb-query mongo-shell


    【解决方案1】:

    幸运的是,您可以很容易地扩展 shell,例如通过在启动 mongo 客户端时执行的 ~/.mongorc.js file 中添加以下方法:

    DBCollection.prototype.findById = function(id) {
        return db.getCollection(this._shortName).find( { "_id" : ObjectId(id) } );
    }
    

    然后你可以执行类似db.collection.findById("55a3e051dc75954f0f37c2f2")

    【讨论】:

      【解决方案2】:

      find({_id: ObjectId("...")}) 的简写是find(ObjectId("..."))

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-06-23
        • 2021-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多