Here's a (possibly) better mini-tutorial on how to get directly into the guts of your MongoDB. This might not solve your specific problem but it should get you as far as the MongoDB version of SELECT * FROM table
.
First of all, you'll want a Mongo::Connection
object. If
you're using MongoMapper then you can call the connection
class method on any of your MongoMapper models to get a connection
or ask MongoMapper for it directly:
connection = YourMongoModel.connection
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.
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)) }
There are also command
and eval
methods on Mongo::DB
that might do what you want.