5

是否有某种与 mongoid 等效的 find_by_sql ,您可以在其中传递一个 mongo 查询并从结果中具体化 Mongoid::Document s?

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 回答