本文介绍了如何直接从Ruby而不是使用Mongoid查询MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为使用MongoDB和Mongoid的Rails应用程序编写迁移.目前,我的迁移使用的模型使用Mongoid来查询和更新记录,但性能不佳.我实质上是在更新大集合中的所有记录并进行n + 20个查询.我花了一个小时在本地运行(但还没有结束),因此取消了迁移.我希望能够毫不费力地对mongo运行原始查询.我假设有某种方法可以从Mongoid访问mongo驱动程序,因为Mongoid已经加载了与数据库的连接.如何访问数据库以直接运行更新查询?

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 performance is sub-par. I am essentially updating all records in a large collection and making n+20 queries. I killed the migration after taking an hour to run locally (and didn't finish). I would like to be able to run raw queries to mongo without too much effort. I'm assuming there is some way to access a mongo driver from Mongoid since Mongoid has already loaded a connection to the database. How can I access the database to run my update queries direcly?

推荐答案

如果您使用的是Mongoid 3,则可以轻松访问其MongoDB驱动程序:.这是不使用模型访问数据而访问一些原始数据的示例:

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

这篇关于如何直接从Ruby而不是使用Mongoid查询MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 23:09