MongoDB For Beginners – Basic Shell Commands (Part II)

In the previous MongoDB’s guide for beginner’s, I’ve covered the importance and terminology of MongoDB as well as how to setup Mongo on Windows and Mac. Resuming where we left off, today we’re going to look into some basic and usefull shell commands for MongoDB.

You can perform almost any action through the Mongo shell. Since this is a beginner’s guide I won’t delve very far down into this rabbit hole. But you better believe there is plenty of documentation on the topic to research further.

MongoDB For Beginners – Introduction and Installation (Part I)

MongoDB For Beginners – Introduction and Installation (Part I)

Learn how to use MongoDB for web development in this comprehensive guide. Part 1 covers the basics to... Read more

Let’s use this small segment to create a collection of TV Shows which we can then reference later using PHP. If you run the command above, you’ll notice there are only two databases installed by default.

> show dbs

We can use the test database and inside create a new collection named “shows” which will hold our TV Show documents. So first I will define a couple of variables inside the shell window.

I’m using three different TV Shows along with their original debut airdate and the television network they ran under.

We need to use the MongoDB .save() command for saving new data and creating new collections.

> a = { title:"Arrested Development", airdate:"November 2, 2003", network:"FOX" }
> b = { title:"Stella", airdate:"June 28, 2005", network:"Comedy Central" } 
> c = { title:"Modern Family", airdate:"September 23, 2009", network:"ABC" }

If you enter each of these lines into the Mongo shell terminal you’ll get a response back with the JSON data formatted. We have just setup 3 variables which can now be passed into the save command for storing each TV Show as a document object in our collection of shows.

If you notice we haven’t actually created any new collection named shows. This is done on-the-fly by MongoDB only after you add some data into a collection. We access and create collections using standard JavaScript dot syntax.

Copy and run the codes below:


This will add each JSON object variable we created into the shows collection. After running the first command on TV Show A we will have a new collection displaying inside our test db. You can verify this by running show collections in the terminal.

But even more interesting, we can check if all the data is saved properly by running the find() query command as below:

> db.shows.find()

In the next article, we’ll take a look into how to setup MongoDB for PHP

MongoDB For Beginners – Setting Up MongoDB For PHP (Part III)

MongoDB For Beginners – Setting Up MongoDB For PHP (Part III)

Before diving into this, I recommend that you read the following related articles if you have not: Introduction... Read more