MongoDB shell 是否有 findById 快捷方式?
Is there a findById shortcut for the MongoDB shell?
我在 mongo DB shell 中最常做的事情是通过 ID 查找对象,例如:
db.collection.find({_id: ObjectId("55a3e051dc75954f0f37c2f2"})
我一遍又一遍地这样做,我发现不得不一遍又一遍地用 ObjectId 包装 id 变得陈旧了。我希望我有一个 findById
-like shorthand 形式,就像 mongoose 提供的那样。我觉得 shell 应该足够聪明,可以理解我的意思,例如:
db.collection.find("55a3e051dc75954f0f37c2f2")
我该怎么做?或者在 mongo shell?
中是否有任何其他方法可以通过 id 进行查询
幸运的是,您可以很容易地扩展 shell,例如,将以下方法添加到启动 mongo
客户端时执行的 ~/.mongorc.js
file:
DBCollection.prototype.findById = function(id) {
return db.getCollection(this._shortName).find( { "_id" : ObjectId(id) } );
}
然后你可以执行db.collection.findById("55a3e051dc75954f0f37c2f2")
find({_id: ObjectId("...")})
的 shorthand 是 find(ObjectId("..."))
。
我在 mongo DB shell 中最常做的事情是通过 ID 查找对象,例如:
db.collection.find({_id: ObjectId("55a3e051dc75954f0f37c2f2"})
我一遍又一遍地这样做,我发现不得不一遍又一遍地用 ObjectId 包装 id 变得陈旧了。我希望我有一个 findById
-like shorthand 形式,就像 mongoose 提供的那样。我觉得 shell 应该足够聪明,可以理解我的意思,例如:
db.collection.find("55a3e051dc75954f0f37c2f2")
我该怎么做?或者在 mongo shell?
中是否有任何其他方法可以通过 id 进行查询幸运的是,您可以很容易地扩展 shell,例如,将以下方法添加到启动 mongo
客户端时执行的 ~/.mongorc.js
file:
DBCollection.prototype.findById = function(id) {
return db.getCollection(this._shortName).find( { "_id" : ObjectId(id) } );
}
然后你可以执行db.collection.findById("55a3e051dc75954f0f37c2f2")
find({_id: ObjectId("...")})
的 shorthand 是 find(ObjectId("..."))
。