Getting Started with MongoDB - Part 1


Ready to get in and start learning about MongoDB, one of the coolest technologies for web developers?

In this new series, you'll go from beginner to pro and be able to use Mongo just as easily as MySQL in your web apps. But first, let's look at the basics.

Why MongoDB?

What if you could store the programmatic models almost exactly like you model them?

In object-oriented development, we're encouraged to approach code development through logical models, so that we can more readily conceptualise it in our mind. When we do this, we're better able discern the logical operations used to interact with it and information that it would contain at different times.

What if you could store the programmatic models almost exactly like you model them? What if you could store them as they are instead of in a series of rows in tables? By learning about MongoDB, you're going to be able to do just that!

In this series, we'll be learning everything from the basics of MongoDb, such as creating, updating and deleting databases and records, to being able to perform complex searches for data and elementary data mining with MapReduce. So, without much ado – let's get started!

Note: This tutorial is done from the perspective of NIX based system a la Mac OSX, Linux BSD and so on. But you should be able to follow along if you're running Windows pretty well as there are builds for most platforms.

Step 1 : Installing Mongo

Ok, so here's where the fun begins. We're going to get started by installing Mongo. Go to the MongoDb website and click on the downloads link.

The MongoDb link to downloads

This will bring you to a page where you can grab a build for your platform and architecture.

The MongoDb download options

This tutorial only covers stable releases, so please do not grab a nightly build. Once it's downloaded, please install it as per the requirements of your platform.

If you're on a Nix machine, then please use its package manager to install the latest version for your platform.

With that out of the way, fire up a terminal and type in mongo. That will open up the Mongo shell and let us get under way. All being well, you'll see output similar to below:

The MongoDb shell

If you see that, then you're ready to go.

Step 2 : Creating a Database/Inserting Records

Initially, no database is created. But don't worry, they'll instantly be created when we start inserting our records, which we're going to do right now. Copy the content below and paste it in your mongo shell

    first: 'matthew',
    last: 'setter',
    dob: '21/04/1978',
    gender: 'm',
    hair_colour: 'brown',
    occupation: 'developer',
    nationality: 'australian'
    first: 'james',
    last: 'caan',
    dob: '26/03/1940',
    gender: 'm',
    hair_colour: 'brown',
    occupation: 'actor',
    nationality: 'american'
    first: 'arnold',
    last: 'schwarzenegger',
    dob: '03/06/1925',
    gender: 'm',
    hair_colour: 'brown',
    occupation: 'actor',
    nationality: 'american'
    first: 'tony',
    last: 'curtis',
    dob: '21/04/1978',
    gender: 'm',
    hair_colour: 'brown',
    occupation: 'developer',
    nationality: 'american'
    first: 'jamie lee',
    last: 'curtis',
    dob: '22/11/1958',
    gender: 'f',
    hair_colour: 'brown',
    occupation: 'actor',
    nationality: 'american'
    first: 'michael',
    last: 'caine',
    dob: '14/03/1933',
    gender: 'm',
    hair_colour: 'brown',
    occupation: 'actor',
    nationality: 'english'
    first: 'judi',
    last: 'dench',
    dob: '09/12/1934',
    gender: 'f',
    hair_colour: 'white',
    occupation: 'actress',
    nationality: 'english'

All good? Excellent! To confirm that the database and accompanying records have been created, type in the following command:


If everything went to plan, then you will see the following output:

Finding all records

This shows that all of the records were created in the database. One thing to note before we go any further is the id field. This is auto generated by Mongo for you, if you don't specify an id. The reason is that every record must have a unique id field.

You can see that we have one record for each of the ones that we insert – now we're ready to start querying them.

Step 3 : Searching For Records

You remember the previous command? It retrieved and displayed every record in the database. Helpful, yes, but how do you be more specific? How do you find all female actors, filtering out the males? That's a good question and the answer is selectors.


Selectors are to Mongo what where clauses are to SQL. As with where clauses, Mongo selectors allow us to do the following:

  • specify criteria that MUST match. i.e., an AND clause
  • specify criteria that CAN optionally match. i.e., an OR clause
  • specify criteria that MUST exist
  • and much more...

Records That MUST Match

Let's start with a basic selector. Say that we want to find all actors that are female
. To accomplish that, you'll need to run the following command:

db.nettuts.find({gender: 'f'});

Here we have specified that gender must be equal 'f'.

Running that command will return the following output:

Finding all female records

What if we wanted to search for male actors? Run the following command:

db.nettuts.find({gender: 'm'});

We'll get the following results:

Finding all male records

Searching with Multiple Criteria

Let's step it up a notch. We'll look for male actors that are English.

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}]});

Running that will return the following results:

Finding all male, English, records

What about male actors who are English or American. Easy! Let's adjust our earlier command to include the Americans:

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]});

For that query, we'll see the following results:

Finding all male, English or American, records

Step 4 : Sorting Records

What if we want to sort records, say by first name or nationality? Similar to SQL, Mongo provides the sort command. The command, like the find command takes a list of options to determine the sort order.

Unlike SQL, however we specify ascending and descending differently. We do that as follows:

  • Ascending: -1
  • Descending: 1

Let's have a look at an example:

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1});

This example retrieves all male, English or American, actors and sorts them in descending order of nationality.

Finding all male, English or American, records sorted by nationality

What about sorting by nationality in descending order and name in ascending order? No problem at all! Take a look at the query below, which is a modified version of the last one we ran.

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).sort({nationality: -1, first: 1});

This time we retrieve the following results et:

Finding all male, English or American, records sorted by nationality first and first name second

You can see that this time Arnold Schwarzenegger is placed before Tony Curtis.

Step 5 : Limiting Records

What if we had a pretty big data set (lucky us, we don't) and we wanted to limit the results to just 2? Mongo provides the limit command, similar to MySQL and allows us to do just that. Let's update our previous query and return just 2 records. Have a look at the following command:

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2);

From that command, we'll get the following results:

Limit output to 2 records

If we wanted the third and fourth records, i.e., skip over the first two? Once again, Mongo has a function for that. Have a look at the further customisation of the previous command:

db.nettuts.find({gender: 'm', $or: [{nationality: 'english'}, {nationality: 'american'}]}).limit(2).skip(2);

Running that will return the following results:

Limit output to the 3rd and 4th records

You can see from the original result set that the first two were skipped.

Step 6 : Updating Records

As expected, Mongo provides an option to update records as well. As with the find method and SQL queries, you need to specify the criteria for the record that you want to modify, then the data in that record that's going to be modified.

Let's say that we need to update the record for James Caan specifying that his hair is grey, not brown. Well for that we run the update function. Have a look at the example below:

db.nettuts.update({first: 'james', last: 'caan'}, {$set: {hair_colour: 'brown'}});

Now when you run that, if all went well, there won't be anything to indicate whether it was a success or failure. To find out if the record was update properly, we need to search for it. So let's do that.

db.nettuts.find({first: 'james', last: 'caan'});

After this you will see the following result:

Update record

This shows that the update worked. One word of caution though, if you don't pass in the $set modifier, then you will replace the record, if it's available, instead of updating it. Be careful!

Step 7 : Deleting Records

I think by this stage, you have really started to get the idea of working with Mongo. That's right, if you want to delete a record, you have to pass in a set of selectors, as you also would with SQL, to determine the set of records to delete. If you don't do this, you will delete all records – and the database.

So, let's say that we don't want James Caan in our list of actors. Let's remove him from the database using the following command:

db.nettuts.remove({first: 'james', last: 'caan'});

As with update, no visible output is provided to indicate whether we were successful or not – so let's do a search to double check.

db.nettuts.find({first: 'james', last: 'caan'});

After this, you should see no results returned. If that's what you've found, then we've successfully deleted James Caan from our database. But what if we want to delete all the records from the database?

Well, to do that, just remove the selectors from the previous call to remove, as below.


After running both commands above, we'll see no output, indicating that the database, with all records have now been removed.

Remove all records


In this rapid introduction to using MongoDB we looked at:

  • What Mongo is
  • How to install it
  • How to create, find, update and delete records

With this knowledge, you can go, practice, and learn more about this wonderful technology. If you want more information, feel free to check out the MongoDb website or follow @mongodb on Twitter.

In the next tutorial, we're going to start to learn more about complex queries. So stay tuned and thank you so much for reading.

Update: The second part of this series has been posted and can be found here.

Related Posts
  • Code
    Web Development
    Creating an RSS Feed Reader With the MEAN Stack Mean wide retina preview
    In the last tutorial we installed the MEAN stack. Now, let's do some actual coding and build an RSS Feed Reader.Read More…
  • Code
    Web Development
    Laravel Unwrapped: Session, Auth and CacheLaravel wide retina preview
    Join me as we learn how to use Laravel's component-based system, Illuminate. Additionally, we'll see how to utilize service providers, Laravel's manager system, the Session, Auth, and Cache components, and the Store, Guard, and Repository libraries.Read More…
  • Code
    Preventing Code InjectionCsrf dotnet retina preview
    Often, websites seem to exist primarily to put something into a database in order to pull it out later. While other database methods, such as NoSQL, have gained popularity in recent years, data for many websites still resides in the traditional SQL database. This data often consists of valuable personal information such as credit card numbers and other personal information of interest to identity thieves and criminals. Hackers therefore always look to get this data. One of the most common targets of these attacks is the SQL databases that lie behind many web applications through a process of SQL Injection.Read More…
  • Code
    Mapping Relational Databases and SQL to MongoDBMongodb retina preview
    NoSQL databases have emerged tremendously in the last few years owing to their less constrained structure, scalable schema design, and faster access compared to traditional relational databases (RDBMS/SQL). MongoDB is an open source document-oriented NoSQL database which stores data in the form of JSON-like objects. It has emerged as one of the leading databases due to its dynamic schema, high scalability, optimal query performance, faster indexing and an active user community.Read More…
  • Code
    Custom Database Tables: Safety FirstCustomdbtables part2
    This is part two of a series about custom database tables in WordPress. In part one we covered the reasons for, and against, using custom tables. We looked at some of the details that would need to be considered - column naming, column types - as well as how to create the table. Before we go any further we need to cover how to interact with this new table safely. In a previous article I covered general sanitisation and validation – in this tutorial we’ll look at this in more detail in the context of databases.Read More…
  • Code
    Getting Started with MongoDB - Part 2Preview
    Ready to continue learning about MongoDB, one of the coolest technologies for web developers? In this second part of the series, we move on from the basics, on to advanced queries - with conditional operators - and MapReduce.Read More…