How to fire raw MongoDB queries directly in Ruby -


is there way can fire raw mongo query directly in ruby instead of converting them native ruby objects?

i went through ruby mongo tutorial, cannot find such method anywhere.

if mysql, have fired query this.

activerecord::base.connection.execute("select * foo") 

my mongo query bit large , executing in mongodb console. want directly execute same inside ruby code.

here's (possibly) better mini-tutorial on how directly guts of mongodb. might not solve specific problem should far mongodb version of select * table.


first of all, you'll want mongo::connection object. if you're using mongomapper can call connection class method on of mongomapper models connection or ask mongomapper directly:

connection = yourmongomodel.connection connection = mongomapper.connection 

otherwise guess you'd use from_uri constructor build own connection.

then need hands on database, can using array access notation, db method, or current 1 straight mongomapper:

db = connection['database_name']    # not support options. db = connection.db('database_name') # support options. db = mongomapper.database           # should configured                                     # rest of app. 

now have nice shiny mongo::db instance in hands. but, want collection interesting , can using either array access notation or collection method:

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

now have behaves sort of sql table can count how many things has or query using find:

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

and have you're after: hot out of oven mongo::cursor points @ data you're interested in. mongo::cursor enumerable have access usual iterating friends such each, first, map, , 1 of personal favorites, each_with_object:

a = cursor.each_with_object([]) { |x, a| a.push(mangle(x)) } 

there command , eval methods on mongo::db might want.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -