Mongoid 3 and Mongodb querying secondaries for specific queries

719 Views Asked by At

I have a mongodb replicaset configured with 3 replicas. My configurations are


staging:
  sessions:
    default:
      hosts:
        - xx.x.x.xxx:27017
        - xx.x.x.xxx:27017
        - xx.x.x.xxx:27017
      database: mongoid_staging
      options:
        consistency: strong
  options:
    allow_dynamic_fields: false
    identity_map_enabled: true
    include_root_in_json: false
    include_type_for_serialization: true

This configuration would ensure that all my writes and reads are always directed to the primary because of the strong consistency. How can i routes specific read queries to the secondaries?

Or to put it another way how can ensure that certain reads are done only from the primary?

I am using Mongoid 3.0.0 and Mongodb 2.2.6. Is this even possible? This article says it can be done with Mongoid 3 but i could not find any thing that tells me how - https://groups.google.com/forum/#!topic/mongoid/pTa4eAWv7gM

Second question:

Can a separate application connect to one of the secondaries in a replicaset and use it as its standalone primary?

1

There are 1 best solutions below

0
On

First of all, I think you understand the consequences of reading and writting to different replicas. You can't guarantee strong consistency. That means that what you read on a secondary may not be up to date. Doing reads and writes from different replicas in the same process makes it even more challenging.

Note also that you should not use the secondaries as a way to off load the primary. The danger is that if the primary goes down, the secondaries may not be able to take the full load.

I am not a fan of ORM, especially for MongoDB, and even less if you use a language like Ruby that supports Map/Hashes/Dicts. Using an ORM makes you loose a lot of control on what you can do with MongoDB and shows weaker performance.

The native Ruby driver for MongoDB has the ability to select the preferred sources for the reads and writes. That is called 'read preference' and you can read more on the subject at:

https://github.com/mongodb/mongo-ruby-driver/wiki/Read-Preference
http://docs.mongodb.org/manual/core/read-preference/

I am not familiar with Mongoid, but you may want to try to pass an additional argument to 'find()', in a similar way that the Ruby driver does. For example, the call to 'find()' would look like:

find({:doc => 'foo'}, :read => :secondary)