Mongoid中的find_by_sql等价方法是什么?

5

在Mongoid中,是否有一种类似于find_by_sql的查询方式,可以通过传递一个Mongo查询语句来从结果中实例化Mongoid::Document对象?

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

这太神奇了!你知道Mongo驱动程序如何知道如何实例化我的Mongoid类吗? - Matt Briggs

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接