The Mongo Shell - Part 5
Rest of the document is written assuming that MongoDB is already installed in the system. If not, please go to the link given
for reference. The terminal commands will be differ for operating systems, but mongo shell commands are same.
Open command prompt and enter mongod to start the mongo server.
On successful installation, it will show port number 27017 below.
Keep current command prompt open, and open another command prompt. Enter mongo on new command prompt, which takes you to mongo shell.
MongoDB shell version: 3.2.0
connecting to: test
Now that we have seen how to open up a shell and interact with MongoDB after installing it. Now we will see how to import documents (JSON files) into mongo before we start working on CRUD operations. Below is the command to import data into database
Mongoimport –db db_name –collection collection_name < path & filename of the JSON (Download products.json from here)
Once this command is executed, it will show number of documents imported into DB. Now data is ready and we can start with playing mongo shell.
Now, to check the available databases, use below command. When doing command line utilities and shell commands, spelling and capitalization get to be very important.
show dbs;
Note: The mongo shell will not show you any databases, unless they are documents in them. So, until we insert some documents and records, it’s not going to show. It’s there, we can use it, but it’s not going to show.
The above output shows the available databases and their size. We will be using pcat database, where we maintaining products document. To switch from one database to another, below is the command
use <dbname>
Here, it is use pcat and the output will be switched to db pcat
Before we move further, I would like to introduce on accessing few list of help commands with descriptions of their use. Examples are
db.help() Help on db methods db.mycoll.help() Help on collection methods sh.help() Sharding helpers show dbs Show database names show users Show users in current database show collections Show collections in current database
Let’s start with some hands-on.
db.createUser() – Creates a new user for the database. When next time user try to login to the database, he should give the id and password defined. Below is the example,
db.createUser({user:”stduser”,pwd:”password”,roles:[“readWrite”,”dbAdmin”]})
Note: Roles is an array, because there is a whole bunch of different roles you could add. We’re only going to put into readWrite and dbAdmin here. The output is
Now enter, show users command to validate the created user (to remind one more time, the documents in MongoDB, will be stored in JSON format only)
The output includes the two previously listed users and the added user – pcat.stduser, with readWrite and dbAdmin roles.