如何从 ruby on rails 应用程序获取 mongodb 数据库列表和集合列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5142900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get list of mongodb databases and collections list from a ruby on rails app
提问by user622773
I am using Rails 3 and Mongoid gem. But I need to fill a combobox with the list of mongodb databases. In mongodb shell we can list databases with "show dbs" command. Also there is getDBNameList() and db.getCollectionNames() commands in mongodb drivers. But I could not figure out how to use these commands from a ruby on rails app.
我正在使用 Rails 3 和 Mongoid gem。但我需要用 mongodb 数据库列表填充一个组合框。在 mongodb shell 中,我们可以使用“show dbs”命令列出数据库。mongodb 驱动程序中还有 getDBNameList() 和 db.getCollectionNames() 命令。但我无法弄清楚如何从 ruby on rails 应用程序使用这些命令。
Also I wonder; if I can get databases and collections list with using mongoid gem. Because I am sure that I had read that mongoid supports using more than one database, but I think it was model dependent.
我也想知道; 如果我可以使用 mongoid gem 获取数据库和集合列表。因为我确信我读过 mongoid 支持使用多个数据库,但我认为它依赖于模型。
So what do you think; is there any solution or I have to use mongo-ruby-driver gem, not mongoid.
所以你怎么看; 有什么解决方案,或者我必须使用 mongo-ruby-driver gem,而不是 mongoid。
回答by Harish Shetty
In mongoid 3
在 mongoid 3
Mongoid.default_session.collections # returns the collections
I usually extract the names as follows:
我通常按如下方式提取名称:
Mongoid.default_session.collections.map(&:name).sort
回答by Steve
You can do the following using the mongo ruby driver:
您可以使用 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
回答by balexand
回答by GutenYe
A short version.
一个简短的版本。
db = Mongoid.master
db.collection_names
回答by Abhi
Using Java driver you can list the database names using the following
使用 Java 驱动程序,您可以使用以下命令列出数据库名称
Mongo mongo = new Mongo( "127.0.0.1" );
mongo.getDatabaseNames();

