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 db.team.find().count(), I ended up hitting enter key a bit too sooner and resultant query in the mongo shell was db.team.find().count  [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..

 

Query.png

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 = db.team.find()
  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 🙂

 

 

 

 

Advertisements