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..
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.
- Grab a collection into variable v.
- var v = db.team.find()
- Find the count of v
- use the convertToCountCmd to get the json object
- var cmd1 = v._convertToCountCmd()
- Execute the runReadCommand to get the details of count.
- Will give the exact count needed.
Below picture depicts the same.
Well, Now thats fun..
Also, Here is how the find() method definition looks like..
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 🙂