gpt4 book ai didi

ruby-on-rails - 如何直接从 Ruby 查询 MongoDB 而不是使用 Mongoid?

转载 作者:IT老高 更新时间:2023-10-28 11:08:07 27 4
gpt4 key购买 nike

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

最佳答案

如果您使用的是 Mongoid 3,它可以轻松访问其 MongoDB 驱动程序:Moped .下面是一个在不使用模型访问数据的情况下访问一些原始数据的示例:

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-on-rails - 如何直接从 Ruby 查询 MongoDB 而不是使用 Mongoid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14816900/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com