The best MongoDB Tutorial on the Web

Even as I write this, there are numerous MongoDB tutorials on the Web, including the official one at www.mongodb.org. They all have a big problem - they all suck. They are either a headache to follow, or miss the basics, or are extremely hard to absorb information from. I want to change that, I want to create the best ever MongoDB tutorial on the Web - a tutorial that efficiently focuses on orienting users to MongoDB.

While this tutorial is not going to be an in-depth article on MongoDB, it will most definitely ensure you a pleasant kickstart of your MongoDB journey.

You may be aware about try.mongodb.org, the online limited-access Mongo shell. Don't bother with it for two reasons: i. This tutorial covers whatever the built-in tutorial there has to offer (and much more), ii. The limitations and bugs in the custom shell might create misconceptions about MongoDB.

I am starting this tutorial assuming you already have MongoDB installed and running on your system. If you haven't installed it yet, get it installed first.

Ok, now that you have MongoDB installed, let's proceed with the tutorial.

First, let's have the MongoDB server running:

$ mongod

Then let's connect to the server using the mongo client:

$ mongo

Note that all the commands in the tutorial will be typed at the mongo client's command prompt >.

Getting acquainted with MongoDB

MongoDB is a document-oriented database system (a kind of NoSQL) made up of the hierarchy of database > collection > document > field > key:value. Here is an approximate comparison between MongoDB and SQL data models.

The similarity (distant) ends at the SQL's row level. It is a good idea to remember the above comparison because I will switch entirely to Mongo-esque from SQL-esque - no more terms like table, row etc.

Next thing to note: the Mongo shell is a fully functional JavaScript shell. You can perform JavaScript operations on data before inserting to or retrieving from the database. The shell supports all standard JavaScript API along with some Mongo-specific custom APIs. I think this feature makes MongoDB an extremely powerful and fascinating database system.

Before you get your hands dirty with the data in the database, I think you should know how to deal with the database system first. Here are the basics of how you interact with MongoDB.

To see the list of databases in the system:

> show dbsbands 0.203125GBmovies (empty)scores (empty)

Just like in SQL, you need to first select a database to be able to perform operations on it. To select a database:

> use moviesswitched to db movies

To find out the currently selected database:

> db.getName()movies

To delete / drop a database, make sure you have selected the database and then do this:

> use scores> db.dropDatabase(){"dropped" : "scores", "ok" : 1 }

To see the collections in a databases:

> show collections

or

> db.getCollectionNames()

Unlike in SQL, databases in MongoDB are created lazily. You don't create databases using any explicit commands. Depending on your commands, the system creates it for you once it determines a database needs to be created. To begin creating a new database, first execute the use command to switch to a new database, and then issue a command which saves some data to the database - this results in the creation on the new database.

That above commands resulted in the creation of the new database named "movies". In the process a new collection called "comedy" was also created in the database.

Now that you know how to handle the database, time to get your hands dirty with the data in the database!

Getting your hands dirty with data in MongoDB

What good is a MongoDB tutorial that does not show how CRUD (Create, Read, Update, Delete) works in MongoDB, preferably with examples? As this tutorial aims to be the best MongoDB tutorial in the world it will show you how CRUD works in MongoDB.

Note: all database commands are called on the MongoDB database object named db. db refers to the database you have selected using the use command.

insert will always add a new document.save does an insert if there is no _id key in the object it receives, else it does an update.

I personally see save to be quite pointless. Unless you are too hooked to the spelling and sound of save, it is recommended to use insert to add new documents to a collection, and update to update collections.

In the above example, we excluded a field by not specifying it in the second parameter of the find() function. To get more than one exclusive fields in the results you might do something like db.comedy.find({year:{'$lt':1994}}, {name:true, director:true}). Note, the director field is still not set, so you won't see any director info.

The _id field is always returned by default. If you want to get rid of it, you need to explicitly do so using the option explained next.

To search an object inside an object, just use the regular JavaScript dot notation of the target object as the key AND quote it. For example, to query the meta.likes object, you might do something like this:

When the key is an array, the database looks for the object right in the array.

You need to look for an object inside an array? No problemo:

> db.articles.find({'comments.by':'Steve'})

You can also refer to array indexes:

> db.articles.find({'comments.0.by':'Steve'})

Isn't that amazing?

Because of the fact that array objects can be matched using the dot notation, it can be problematic if the objects in an array share the same keys but different values. In such cases, we need to use the $elemMatch operator. To see an example and understand the issue better, read this.

Always remember that a quoted number is a string, and is not the same as the actual number. For example:

> db.students.find({score:100})

is totally different from

> db.students.find({score:'100'})

In general, form request parameters come as strings, so you are likely to be querying for the stringified version of numbers in your web apps if you use the parameters as such. Make sure to convert them to their number equivalent wherever necessary first. For example in Express, you can do this:

var score = +params.score;

params.score is a string, but score is now an actual JavaScript number, which can be reliably used in a MongoDB query.

MongoDB queries support JavaScript expressions! Take a look at this example:

As easy as that! But there's lot more to updating that just those, for details click here.

Delete data in MongoDB

How do you delete a field from a document?

> db.comedy.update({name:'Hulk'}, {$unset:{cast:1}})

In case you want to delete a field from all the document of a collection:

> db.comedy.update({$unset:{cast:1}}, false, true)

The false parameter if for upsert option, true is for multiple option. We set multiple option to true because we want to delete them all from the collection. In my opinion this is an inconsistency. It should work like find() and findOne(), when it comes to selection.

How do you delete a document from a collection?

> db.comedy.remove({name:'Hulk'})

In the above example, we deleted all the documents with their name field set as Hulk.

How do you empty a collection of its documents?

> db.comedy.remove()

Note, the above command does not delete the collection, it just 'resets' the collection like the SQL truncate command.

How do you delete / drop a collection?

> db.comedy.drop()

The above command actually deletes the collection.

To delete a database select the database and call the db.dropDatabase() on it:

> use movies> db.dropDatabase(){"dropped" : "movies", "ok" : 1 }

That deletes the database named movies.

Get the count of Documents / Records

Any good database system should have a count() method which returns the number of records that will be returned for a query. MongoDB too has a count() method which you can call on a collection to get the count of the results.

This will return the total number of documents in the collection named comedy:

> db.comedy.count({})

This will return the total number of documents in the collection named comedy with the value of year more than 1990:

> db.comedy.count({year:{$gt:1990})

So basically that's about it. There is a ton more to MongoDB than what I covered, I have listed the pointers at the Further Reading section, read all of them.

I hope you found this tutorial useful. I will be writing many more MongoDB related articles and tutorials in the future, so stay tuned. If you have any orientation / beginner level questions, feel free to ask me in the comments.