Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a findById shortcut for the MongoDB shell?

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?

like image 528
Andrew Lavers Avatar asked Jul 15 '15 16:07

Andrew Lavers


2 Answers

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")

like image 131
mnemosyn Avatar answered Sep 27 '22 22:09

mnemosyn


The shorthand for find({_id: ObjectId("...")}) is find(ObjectId("...")).

like image 20
Camilo Avatar answered Sep 27 '22 23:09

Camilo