In the past couple of weeks, I had the opportunity to look at MongoDB and Redis in more details. Both are fast, but serve different needs. Here’s my take on them both.

MongoDB

MongoDB is a document oriented database. MongoDB stores structured data, as documents:

1 {
2   'name': 'Fran├žois Beausoleil',
3   'email': 'francois@teksol.info',
4   'year-of-birth': 1973,
5   'tags': ['friendly', 'ruby', 'coder', 'father']
6 }

Since MongoDB stores structured data, it has a richer query language:

 1 // Find people that are fathers OR coders
 2 db.people.find( { "tags" : { $in : ['father', 'coder'] } } );
 3 
 4 // Find people that are fathers AND coders
 5 db.people.find( { "tags" : { $all : ['father', 'coder'] } } );
 6 
 7 // Index the email member of documents
 8 db.people.ensureIndex({email: 1});
 9 
10 // Query using the index
11 db.people.findOne({email: 'francois@teksol.info'})

Redis

Redis is a key-value store that is strongly typed. Redis has three types of values: strings, sets and lists. Out of the box, you cannot store structured data in Redis. You have to build the index manually, storing yet other keys.

Redis is conceptually simple. All operations are either stores or fetches:

1 PUT key value
2 GET key

You can think of Redis as a persistent Hash or Dictionary. The fact that Redis is strongly typed makes some operations very interesting.

 1 # Store other data as serialized JSON object, but we won't be able to query the value itself
 2 SET "people:francois" "{'name': 'Fran├žois Beausoleil', 'email': 'francois@teksol.info', 'year-of-birth': 1973, 'tags': ['friendly', 'ruby', 'coder', 'father']}"
 3 
 4 # Build ourselves an index on the email value
 5 SET "email:francois@teksol.info" "francois"
 6 
 7 # Build another index for tags
 8 SADD "tags:friendly" "francois"
 9 SADD "tags:ruby"     "francois"
10 SADD "tags:coder"    "francois"
11 SADD "tags:father"   "francois"
12 
13 # During authentication, we would find the person using the email address
14 GET "email:francois@teksol.info"
15 
16 # Get the rest of the data
17 GET "people:francois"
18 
19 # Find the keys that have both father AND coder as tags
20 SINTER "tags:father" "tags:coder"

Conclusion

So, which one should you choose? The short answer is “it depends”.

The longer answer is to use the best tool for the job. Storing documents is different than storing simple key values. Of course, both can be used for the same job, but Redis will be easier if you need a simple Hash/Dictionary. Use MongoDB for storing structured data.

Search

Your Host

A picture of me

I am François Beausoleil, a Ruby on Rails and Scala developer. During the day, I work on Seevibes, a platform to measure social interactions related to TV shows. At night, I am interested many things. Read my biography.

Top Tags

Books I read and recommend

Links

Projects I work on

Projects I worked on