MongoDB Shell Functions – Can we customize ?

While working on MongoDB, I accidentally ran a find() count query incorrectly which resulted in something interesting.

While I wanted to execute, I ended up hitting enter key a bit too sooner and resultant query in the mongo shell was  [yeah, without the ()]

While I was expecting an error, the shell actually responded with the function definition of count() method and it goes as below..



So, above is what exactly happens when we call find().count() in the shell.

So with this, you can start looking into the design and implementation of shell functions and understand the login underneath.


Interpreting the query definition ourselves, we can get the count of collection as below as well.

  1. Grab a collection into variable v.
    • var v =
  2. Find the count of v
    • v.count()
  3. use the convertToCountCmd to get the json object
    • var cmd1 = v._convertToCountCmd()
  4. Execute the runReadCommand to get the details of count.
    • db.runReadCommand(cmd1)
  5. db.runReadCommand(cmd1).n
    • Will give the exact count needed.

Below picture depicts the same.

Query2.png Well, Now thats fun..



Also, Here is how the find() method definition looks like..Query1

One final thought before ending this blog post, will MongoDB allow us to extend the functionality of these methods? For Ex, can i create my own custom Count method using or my own shell function ? At this moment i’m not sure..

Calling all #Mongo experts to answer 🙂






Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s