0

I am running a Rails application and using MongoDB as database store. For the data mapping part I use the MongoMapper gem.

MongoMapper is great if I want to mimic the functionality of ActiveRecord models, but my question is if it is possible or not to run simple MongoDB queries thorugh MongoMapper, like directly querying a collection(namely without an explicit Model, who includes the fields and so on) or I should use the mongo gem for ruby?

Thank you

Victor Blaga
  • 1,822
  • 4
  • 19
  • 28
  • possible duplicate of [How to fire raw MongoDB queries directly in Ruby](http://stackoverflow.com/questions/6548061/how-to-fire-raw-mongodb-queries-directly-in-ruby) – mu is too short Nov 03 '11 at 16:12

1 Answers1

0

I stole this mostly from How to fire raw MongoDB queries directly in Ruby

connection = MongoMapper.connection

Otherwise I guess you'd use the from_uri constructor to build your own connection.

Then you need to get your hands on a database, you can do this using the array access notation, the db method, or get the current one straight from MongoMapper:

db = connection['database_name']    # This does not support options.
db = connection.db('database_name') # This does support options.
db = MongoMapper.database           # This should be configured like
                                # the rest of your app.

Now you have a nice shiny Mongo::DB instance in your hands. But, you probably want a Collection to do anything interesting and you can get that using either array access notation or the collection method:

collection = db['collection_name']
collection = db.collection('collection_name')

Now you have something that behaves sort of like an SQL table so you can count how many things it has or query it using find:

cursor = collection.find(:key => 'value')
cursor = collection.find({:key => 'value'}, :fields => ['just', 'these', 'fields'])

etc.

output a row

cursor.each { |row| puts row } 

And now you have what you're really after: a hot out of the oven Mongo::Cursor that points at the data you're interested in. Mongo::Cursor is an Enumerable so you have access to all your usual iterating friends such as each, first, map, and one of my personal favorites, each_with_object:

a = cursor.each_with_object([]) { |x, a| a.push(mangle(x)) }
Community
  • 1
  • 1
jmontross
  • 3,533
  • 1
  • 21
  • 17