MongoDB query optimisation

1:32 AM 0 Comments

 Before you read below, make sure MongoDB is the right choice for your application. It's Nonrelational and Document oriented database.

Mongoid::Criteria Let's say you query all user data, @users = User.all while using mongoid. So when you access @users in views, it's Mongoid::Criteria and
ruby methods will not work ex- to_json. When we iterate over @users, say

@users.each do |user| 
  p user
end

For each user entry, query is fired which could easily be avoided by changing the query to @users = User.all.entries or @users = User.all.to_a. Also for single object @user = User.where(email: "bijendra.biju@gmail.com").first.

Index your database: use the specific fields while indexing which will fasten the search. Indexes improve the efficiency of read operations by reducing the amount of data that query operations need to process.
Apart from read operations indexes can support sort operation and allow for a more efficient storage utilization.

For ex: If you need to implement search over user database, index the specific fields which will be used for searching. By default _id will be created and indexed,


class User
  include Mongoid::Document
  field :name, :type => String
  field :email, :type => String
  index({ email: 1 })
end

http://docs.mongodb.org/manual/core/map-reduce/
http://docs.mongodb.org/manual/core/aggregation-pipeline/

Bijendra Singh

Some say he’s half man half fish, others say he’s more of a seventy/thirty split. Either way he’s a fishy bastard.

0 comments: