How to query MongoDB directly from Ruby instead of using Mongoid?

前端 未结 7 482
刺人心
刺人心 2020-12-24 06:33

I am writing a migration for a Rails application that uses MongoDB and Mongoid. My migration currently uses my models that use Mongoid to query and update records, but the p

7条回答
  •  鱼传尺愫
    2020-12-24 06:53

    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
    
    # inserting a new document
    collection = db[:collection_name]
    collection.insert(name: 'my new document')
    
    # finding a document
    doc = collection.find(name: 'my new document').first
    
    # iterating over all documents in a collection
    collection.find.each do |document|
      puts document.inspect
    end
    

提交回复
热议问题