In Mongo we trust

26 April 2016

10 minute crash course in MongoDB

Recently I've been working more and more with MongoDB, I previously worked heavily with Couchbase and blogged a lot about how to query Couchbase if coming from the SQL world. The following is a ten minute crash course in the most common queries you'll want to execute when using MongoDB or you have an interview and forgot to prep!

MongoDB 10'000m overview

MongoDB is an open-source document based database that stores data in BSON (Binary Json). Instead of a traditional table based relational database MongoDB works with documents that are schema-less and hence can be much more flexible in terms of what data can be stored together in the same collection.

As Mongo is schema-less you lose a distinct advantage of traditional RDBMS and that is the ability to perform joins between multiple tables, this means that often with Mongo data will be replicated into different collections and multiple queries often have to be executed to extract the same data that usually you'd be able to run with one SQL query. Mongo is really fast so don't sweat it about having to execute multiple requests.

Having said the above Mongo really shines when working with unstructured data, being able to store different types of data on the fly can be useful, just make sure you are picking the correct tool for the job.

Time to get set up

We're going to load in some sample data and start executing some queries, it's the fastest way to learn how to work with Mongo. All this assumes you have MongoDB running locally on your machine. Save the following JSON file locally:

Running the following command will load the data from above into MongoDB under a database name of inmongowetrust and a collection of users. (Think of collections as being similar to tables in the RDBMS world).

From the tools I've tried for running test queries and working with data RoboMongo. If you run the following queries in RoboMongo you'll easily see which documents are being returned and can easily experiment with the result sets!