代码之家  ›  专栏  ›  技术社区  ›  Matt Briggs

查找MongoID的等效SQL?

  •  5
  • Matt Briggs  · 技术社区  · 15 年前

    是否有类似于mongoid的find-by-sql,在这里传递一个mongo查询并从结果中具体化mongoid::document s?

    2 回复  |  直到 15 年前
        1
  •  8
  •   PreciousBodilyFluids    15 年前

    mongoid包装集合对象以返回适当类的对象。

    因此,如果用户是MongoID模型:

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

    编辑添加:它实际上也包装了Mongo的光标类。 See here:

    def each
      @cursor.each do |document|
        yield Mongoid::Factory.build(@klass, document)
      end
    end
    
        2
  •  2
  •   Andrew    13 年前

    如果您使用的是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