MongoDB For Beginners: Basic Shell Commands (Part 2/3)

By . Filed in Web Design

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.

MongoDB Mac OS X Terminal list databases

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.

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:

> db.shows.save(a)
> db.shows.save(b)
> db.shows.save(c)

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. Stay tuned!

Author:

Jake is a user experience designer for both web and mobile platforms. Having over 4 years of freelance projects under his belt, he frequently writes articles on topics of modern design trends and social media. You can check out some of his work on Dribbble or follow his tweets @jakerocheleau.

Advertisement