5

mongoidに相当するfind_by_sqlのようなものはありますか?ここでは、mongoクエリを渡し、結果からMongoid :: Documentを具体化しますか?

4

2 に答える 2

8

Mongoid は Collection オブジェクトをラップして、適切なクラスのオブジェクトを返します。

したがって、 User が Mongoid モデルの場合:

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

編集して追加: 実際には Mongo の Cursor クラスもラップします。ここを参照してください:

def each
  @cursor.each do |document|
    yield Mongoid::Factory.build(@klass, document)
  end
end
于 2010-09-16T20:28:22.443 に答える
2

Mongoid 3 を使用している場合は、MongoDB ドライバーであるMopedに簡単にアクセスできます。モデルを使用せずに生データにアクセスする例を次に示します。

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
于 2013-07-08T22:19:54.173 に答える