mongoid query caching

Roman picture Roman · May 24, 2011 · Viewed 8.9k times · Source

Rails' ActiveRecord has a feature called Query Caching (ActiveRecord::QueryCache) which saves the result of SQL query for the life-span of a request. While I'm not very familiar with the internals of the implementation, I think that it saves the query results somewhere in the Rack env, which is discarded in the end of the request.

The Mongoid, unfortunately, doesn't currently provide such feature, and this is exacerbated by the fact, that some queries occur implicitly (references). I'm considering to implement this feature, and I'm curious, where and how Mongoid (or, perhaps, mongo driver?) should be hooked in order to implement this.

Answer

asaaki picture asaaki · May 27, 2011

Mongoid has caching, described under http://mongoid.org/en/mongoid/docs/extras.html

Also MongoDB itself has caching ability: http://www.mongodb.org/display/DOCS/Caching

The mongoid caching extra knows 2 different cases: Caching of all queries of a model or caching of a query.

Mongoid caching seems to work slightly different: it looks like mongoid delegates caching to mongodb. (In the sources of mongoid I only can find option settings for caching but no cache module.)

Finally would say, there is no real difference in the caching in general -- in memory is in fact in memory! No matter if it's in the app or in the database.

I don't prefer to implement an extra caching algorithm, because this seems to be redundant and a RAM killer.

BTW: If your really want to cache results in-app you could try Rails.cache or another cache gem as a workaround.