MongoDB MongoMapper Ruby Replica Set Config
I ended up doing this:
MongoMapper.connection = Mongo::MongoReplicaSetClient.new(
['10.5.5.5:27017', '10.5.5.6:27017'],
:read => :primary, :rs_name => 'name', :connect_timeout => 30, :op_timeout => 30
)
MongoMapper.database = "db_name"
MongoMapper.database.authenticate("user", "test123")
Works beautifully.
rails 4 with mongoid or mongomapper ? which is perfect for own product
Mongoid has been officially incorporated under the MongoDB umbrella. It is a more mature product and it's actively developed, compared with MongoMapper.
I'd definitely not use MongoMapper for a new project.
What is the difference between mongodb and mongomapper?
MongoMapper is just a Ruby API for connecting to, querying, and updating a MongoDB databse.
How to do build this mongoDB query (mongomapper)
Thanks to @Simon I had a look at Map Reduce with MongoMapper. My take on it is probably not perfect, but it does what I want it to do. Here's the implementation:
class ChildTemplate
...
key :name, String
key :version, Integer, :default => 1
...
private
def self.map
<<-JS
function() {
emit(this.name, this);
}
JS
end
private
def self.reduce
<<-JS
function(key, values) {
var res = values[0];
for(var i=1; i<values.length; i++)
{
if(values[i].version > res.version)
{
res = values[i];
}
}
return res;
}
end
def self.latest_versions(opts = {})
results = []
opts[:out] = "ct_latest_versions"
ChildTemplate.collection.map_reduce(map, reduce, opts).find().each do |map_hash|
results << map_hash["value"]
end
return results
end
Find documents including element in Array field with mongomapper?
In the current versions of MongoMapper, this will work:
MessageThread.where(:partecipant_ids => 15)
And this should work as well...
MessageThread.where(:partecipant_ids => [15])
...because plucky autoexpands that to:
MessageThread.where(:partecipant_ids => { :$in => [15] })
(see https://github.com/jnunemaker/plucky/blob/master/lib/plucky/criteria_hash.rb#L121)
I'd say take a look at your data and try out queries in the Mongo console to make sure you have a working query. MongoDB queries translate directly to MM queries except for the above (and a few other minor) caveats. See http://www.mongodb.org/display/DOCS/Querying
Advice on migrating from MongoMapper to Mongoid?
Both of them are great MongoDB Libraries for Ruby. But if you want to switch, here are some notes:
Migrating MongoMapper ORM to Mongoid ORM - Notes
Configure the database connection.
Replace configuration yaml file(includes replica configuration).
Configure Mongoid specific options. e.g -
raise_not_found_error: false
. if you don't want an error every time a query returns nothing...Change all models definations -
include MongoMapper::Document
toinclude Mongoid::Document
Change the format for all fields definitions.
In mongoid, you should specipy the timestamp:
include Mongoid::Timestamps
Change validation. e.g:
:in => ARRAY
, will be:validates :name, presence: true, inclusion: { in: ARRAY }
Change indexes.
Change order_by format. e.g: MM:
Model.all(:order => 'name')
. Mongoid:Model.order_by('name ASC')
Error
is a keyword in Mongoid. So if you have a model namedError
, you should change it.Pagination format is different, using another gem.
The primary key index entry in MM is
id
. In Mongoid it's_id
, if you have other code relying on.id
in the object JSON, you can override as_json function in your Model to create the JSON structure you want.In MM,
Model.fields(:id, :name)
,limits the fields returned from the database to those supplied to the method. In Mongoid it'sModel.only(:name,:id)
Some queries changes:
Selecting objects by array: MM:
Model.where(:attr.in => [ ] )
andModel.where(:attr => [ ] )
. Mongoid is only:Model.where(:attr.in => [ ] )
Map option of MM is equivalent to the Mid's pluck.
Model.map(&:name)
--to--Model.pluck(:name)
Mongoid doesn't support find query for nil. e.g:
value = nil. Model.find(value)
will throw an error :"Calling Document .find with nil is invalid"
. So in mongoid we should do:Model.find(value || "")
.In MM:
Model.find_or_initialize_by_name("BOB")
. In MongoidModel.find_or_initialize_by(name: "BOB")
.MM can be used in those two options:
Model.where({:name => 'BOB'}).first
, and alsoModel.first({:name => 'BOB'})
. Mongoid has only first option.In MM, to update multiple objects:
Model.set({conditions},attr_to_update)
. In Mongoid:Model.where(conditions).update_all(attr_to_update)
.
Rails and MongoDB with MongoMapper
Changed the Task entity from EmbeddedDocument to Document, and deleted the
validates_associated: task from Project, it's now working updating, adding and
deleting tasks from updating a Project.
Thanks a lot to x1a4 and John Nunemaker for the help :-)
Related Topics
Mixing Jsf El in a JavaScript File
Ckeditor 4: Uncaught Typeerror: Cannot Read Property 'Langentries' of Null
How to Include HTML in a Js Rails Response
How Persistent Is Localstorage
Ruby on Rails 4 JavaScript Not Executed
How to Use Ranges in a Switch Case Statement Using JavaScript
Multiple, Sequential Fetch() Promise
Improving Performance of Click Detection on a Staggered Column Isometric Grid
How Does a Function in a Loop (Which Returns Another Function) Work
How to Detect Scroll Position of Page Using Jquery
Selectionstart/Selectionend on Input Type="Number" No Longer Allowed in Chrome
How Is a JavaScript String Not an Object
JavaScript with Embedded Ruby: How to Safely Assign a Ruby Value to a JavaScript Variable
Can a Site Invoke a Browser Extension