In this blog post I go over some tips and tricks with MongoDB and focus on using the mongodbshell.
What is MongoDB
MongoDB is a document database with the scalability and flexibility that you want with the querying and indexing that you need.
MongoDB is released as two editions: Community and Enterprise.
Community is the open source release of MongoDB.
Enterprise provides additional administration, authentication, and monitoring features.
Installation steps vary depending on the edition; both procedures are outlined in this section.
Starting interactive mongodb session
Once you have installed mongodb you need to make sure that is running and then you can simply type:
and then get into an interactive mongo shell session:
Pretty Print trick for mongodb
You can set global settings in mongodb interactive shell in the $SHELL/.mongorc.js configuration file.
In mongodb shell if you want to pretty print collections you need to use the pretty() function like this:
If we set the following values in our ~/.mongorc.js:
Now with this new setting we can simply query for documents and get pretty printing by default:
Notice here that we did not specify the
.pretty() function and got pretty print behavior by default.
Setting default number of documents printed to standard output
You can set the number of documents to show at a time with the following setting in *$HOME/.mongorc.js:
DBQuery.shellBatchSize = 25
Set the settings for a mongodb server with the following command:
You can see the setting for the mongodb server with this command in the interactive shell:
You can easily extend the available functions in mongo shell by adding them on ~/.mongorc.js configuration file:
Now you can easily use this new function in a new mongo shell session like this:
The mongostat utility provides a quick overview of the status of a currently running mongod or mongos instance.
mongostat is functionally similar to the UNIX/Linux file system utility vmstat, but provides data regarding mongod and mongos instances.
Finding the timestamp for when a particular document was added
You can run the
ObjectId("").getTimestamp() to get the timestamp for the added mongo document
Using ESNext features in mongo shell session