MongoDB Logo
Have you ever heard about MongoDB? It’s a document-oriented NoSQL database. Instead of keeping data in familiar SQL-tables MongoDB keeps them as collections of JSON-like documents.

Intrigued? Read this tutorial and you will get a general impression about this database in just a minute.

Installation

MongoDB can be installed on Linux, OS X or Windows. I will not go into details here, but just mention that on my Mac it took only 3 minutes to start using MongoDB from scratch. These four commands establish it installed and running on your Mac:

If you want to taste MongoDB without installing it on your computer, then you can use this online shell to test it right in your browser.

Adding Data

If the MongoDB engine is already running on your machine, you can start playing with it by means of an interactive JavaScript mongo shell. Just run “mongo” and you will see  its prompt inviting you to execute MongoDB commands (which are JavaScript-like).

Lets start with database creation and data insertion:

The first line starts the mongo shell. Then you can see MongoDB commands (preceded with “>” prompt):

  • The first command creates a new “testDB” database and selects it as current.
  • The second command inserts a new document containing one field, “name”, with the value, “my first document”, into a new collection, “testCollection”, in our database

If you’re already familiar with SQL terminology, then you will easily get the MongoDB’s equivalents:

  • database in SQL = database in MongoDB
  • table in SQL = collection in MongoDB
  • row in SQL  = document in MongoDB
  • column in SQL = field in MongoDB

Note: MongoDB automatically adds a unique identifier, “_id”, to all newly created documents.

Querying Data

To query documents from MongoDB database you can use  .find() or .findOne methods of collection, for example

returns one document from “users” collection that has “name” field equal to “admin”.

You can also run more complicated queries, for example this aggregated query

is equivalent to

Updating Data

In the same way it is pretty easy to update records in MongoDB. For example, the following command renames the user with name “admin” to “superadmin”:

Conclusion

I think these examples have already given you some impression of what MongoDB is. The first difference from traditional SQL databases is that each document in a collection may have its own set of fields, while all the rows of the same table in SQL database must have the same set of columns. Another obvious difference is that with MongoDB you use familiar JavaScript language to work with database, not SQL.