MongoDB basics for everyone – Part 3 Database Commands

In a relational database, we would normally do something along the lines of CREATE DATABASE `somedb` and then USE that database. MongoDB is slightly different in this regard as MongoDB does not use a traditional “schema”, but more of a “dynamic schema”. We will get to more on this a little later, but do keep it in mind.

If you haven’t already, connect to the Mongo shell with mongo in a terminal window or command prompt. We will be working with a database called tutorial that will contain a number of collections. In order to connect to the database, enter the use tutorial command. You will notice that we did not need to create a database explicitly and we are now connected to the tutorial database. You can confirm this by simply entering db at the mongo shell prompt, which will return the current database.

Enter the command show collections into the shell now and see what it returns. There should be a single collection called system.indexes available to you. This is a system collection that stores the indexes for this database, so you need not worry too much about it for the purposes of this book.

Remember that dynamic schema? We are now going to exploit that again to create a new collection and insert a document to that collection in one smooth operation.

Now would probably be a good time to introduce the “query language” that MongoDB uses, but for now, we will simply note that all queries need to be structured in valid JSON (actually BSON, but we will cover that later too).

We will now quickly insert a document to a new collection called testcollection with a single key “test”, with the value of 1.


Simple as that! Lets have a quick look at our collections again and you should see that we now have an additional collection. Great news! One last thing that we need to do is to check that our JSON document is indeed in the database, which we can determine with


which should return a single record. In the next chapter, we will look closer at the find() and findOne() commands for MongoDB. A last command that I would like to introduce quickly is the show dbs command. Show dbs will always print out a list of the databases wherever you are, much like the SHOW DATABASES; command in MySQL.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>