The most common thing I do in the mongo DB shell is find objects by ID, eg:
db.collection.find({_id: ObjectId("55a3e051dc75954f0f37c2f2"})
I do this over and over and I find having to wrap the id with ObjectId over and over gets old. I wish I had a findById
-like shorthand form like what mongoose provides. I feel like the shell ought to be smart enough to figure out what I mean here for example:
db.collection.find("55a3e051dc75954f0f37c2f2")
How might I do this? Or are there any alternative ways of querying by id in the mongo shell?
Fortunately, you can extend the shell quite easily, for example by adding the following method to the ~/.mongorc.js
file which is executed when you start the mongo
client:
DBCollection.prototype.findById = function(id) {
return db.getCollection(this._shortName).find( { "_id" : ObjectId(id) } );
}
Then you can execute something like db.collection.findById("55a3e051dc75954f0f37c2f2")
The shorthand for find({_id: ObjectId("...")})
is find(ObjectId("..."))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With