Showing posts with label MongoDB. Show all posts
Showing posts with label MongoDB. Show all posts

Monday, March 17, 2014

A Few ObjectId Tricks

http://www.mongotips.com/b/a-few-objectid-tricks/

To and From Strings

First off, it is quite simple to switch back and forth between object id and string, which is useful in JSON/XML serialization and in finding Mongo documents from params.
id = BSON::ObjectId.new 
# => BSON::ObjectId('4d6e5acebcd1b3fac9000002') 
id.to_s 
# => "4d6e5acebcd1b3fac9000002" 
BSON::ObjectId.from_string(id.to_s) 
# => BSON::ObjectId('4d6e5acebcd1b3fac9000002') 

Generation Time

Switching back and forth between strings is simple and obvious. Something a little more interesting is that pretty much every driver supports extracting the generation time from an object id. This means that you can stop using created_at in your Mongo documents and instead just pull it from the object id. We are doing this in Gaug.es quite often.
BSON::ObjectId.new.generation_time 
# => 2011-03-02 15:01:08 UTC
The generation time is UTC and you can easily use ActiveSupport’s awesome TimeZone stuff to move the time into different zones.

id = BSON::ObjectId.new 
id.generation_time.in_time_zone(Time.zone)

Saturday, March 15, 2014

Tuesday, February 11, 2014

ReactiveMongo - Asynchronous & Non-Blocking Scala Driver for MongoDB

https://github.com/ReactiveMongo/ReactiveMongo
Scale better, use less threads
With a classic synchronous database driver, each operation blocks the current thread until a response is received. This model is simple but has a major flaw - it can't scale that much.
Imagine that you have a web application with 10 concurrent accesses to the database. That means you eventually end up with 10 frozen threads at the same time, doing nothing but waiting for a response. A common solution is to rise the number of running threads to handle more requests. Such a waste of resources is not really a problem if your application is not heavily loaded, but what happens if you have 100 or even 1000 more requests to handle, performing each several db queries? The multiplication grows really fast...
The problem is getting more and more obvious while using the new generation of web frameworks. What's the point of using a nifty, powerful, fully asynchronous web framework if all your database accesses are blocking?
ReactiveMongo is designed to avoid any kind of blocking request. Every operation returns immediately, freeing the running thread and resuming execution when it is over. Accessing the database is not a bottleneck anymore.