Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find_by_sql equivalent for mongoid?

Is there some sort of find_by_sql equivalent for mongoid, where you pass a mongo query and it materializes Mongoid::Document s from the results?

like image 842
Matt Briggs Avatar asked Sep 16 '10 20:09

Matt Briggs


2 Answers

Mongoid wraps the Collection object to return objects of the proper class.

So, if User is a Mongoid model:

cursor = User.collection.find({}, {}) # Just like the Ruby driver...
records = cursor.to_a # An array of User objects

Edit to add: It actually wraps Mongo's Cursor class too. See here:

def each
  @cursor.each do |document|
    yield Mongoid::Factory.build(@klass, document)
  end
end
like image 124
PreciousBodilyFluids Avatar answered Sep 19 '22 03:09

PreciousBodilyFluids


If you're using Mongoid 3, it provides easy access to its MongoDB driver: Moped. Here's an example of accessing some raw data without using Models to access the data:

db = Mongoid::Sessions.default
collection = db[:collection_name]

# finding a document
doc = collection.find(name: 'my new document').first

collection.find.each do |document|
  puts document.inspect
end
like image 34
Andrew Avatar answered Sep 17 '22 03:09

Andrew