6

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?

Penny Liu
  • 15,447
  • 5
  • 79
  • 98
Andrew Lavers
  • 8,023
  • 1
  • 33
  • 50

2 Answers2

6

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

mnemosyn
  • 45,391
  • 6
  • 76
  • 82
3

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

Camilo
  • 6,504
  • 4
  • 39
  • 60