【问题标题】:How to get list of mongodb databases and collections list from a ruby on rails app如何从 ruby​​ on rails 应用程序获取 mongodb 数据库列表和集合列表
【发布时间】:2011-07-05 19:13:18
【问题描述】:

我正在使用 Rails 3 和 Mongoid gem。但我需要用 mongodb 数据库列表填充一个组合框。在 mongodb shell 中,我们可以使用“show dbs”命令列出数据库。 mongodb 驱动程序中还有 getDBNameList() 和 db.getCollectionNames() 命令。但我不知道如何从 ruby​​ on rails 应用程序中使用这些命令。

我也想知道;如果我可以使用 mongoid gem 获取数据库和集合列表。因为我确信我已经阅读过 mongoid 支持使用多个数据库,但我认为它取决于模型。

那么你怎么看?有什么解决方案,或者我必须使用 mongo-ruby-driver gem,而不是 mongoid。

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    在mongoid 3中

    Mongoid.default_session.collections # returns the collections
    

    我通常将名称提取如下:

    Mongoid.default_session.collections.map(&:name).sort
    

    【讨论】:

    • default_session 是 mongo 5 中的 default_client
    【解决方案2】:

    一个简短的版本。

    db = Mongoid.master
    db.collection_names
    

    【讨论】:

    • 你会如何使用 Mongoid 3.0.0 来做到这一点?
    【解决方案3】:

    从 Mongoid 配置中取出 Mongo::DB 会更容易:

    db = Mongoid::Config.master
    db.collection_names
    

    【讨论】:

    • 我们可以配置Mongoid中的所有数据库(通过mongoid.yml) dbs = Mongoid.databases dbs.each do |db| db.collections 结束
    • connection = Mongoid.master.connection connection.database_names #=> 获取名称数组 db = connection.database("name") #=> 获取特定的 db 对象 db.collections #=>获取集合数组#####我认为这是最好的方法;感谢 durran(来自 github)。
    • 这似乎对我不起作用(在 mongoid 3.x 上):NoMethodError: undefined method `master' for Mongoid::Config:Module
    • 我和@turboladen有同样的问题,有什么办法解决吗?
    • @DavidSilveira:不幸的是,我不能告诉你我是否这样做了——我已经很久没有使用那个应用程序了。不过祝你好运!
    【解决方案4】:

    您可以使用 mongo ruby​​ 驱动程序执行以下操作:

    require 'rubygems'
    require 'mongo'
    
    connection = Mongo::Connection.new("localhost")
    connection.database_names.each do |name|
      db = connection.db(name)
      db.collections.each do |collection|
        puts "#{name} - #{collection.name}"
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 1970-01-01
      • 1970-01-01
      • 2013-05-27
      • 2019-01-13
      • 1970-01-01
      相关资源
      最近更新 更多