How to get list of mongodb databases and collectio

2019-02-02 00:43发布

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.

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.

So what do you think; is there any solution or I have to use mongo-ruby-driver gem, not mongoid.

5条回答
淡お忘
2楼-- · 2019-02-02 01:07

You can do the following using the mongo ruby driver:

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
查看更多
不美不萌又怎样
3楼-- · 2019-02-02 01:09

Using Java driver you can list the database names using the following

Mongo mongo = new Mongo( "127.0.0.1" );
mongo.getDatabaseNames();
查看更多
Fickle 薄情
4楼-- · 2019-02-02 01:11

It would be easier to get the Mongo::DB out of the Mongoid config:

db = Mongoid::Config.master
db.collection_names
查看更多
看我几分像从前
5楼-- · 2019-02-02 01:19

A short version.

db = Mongoid.master
db.collection_names
查看更多
Fickle 薄情
6楼-- · 2019-02-02 01:20

In mongoid 3

Mongoid.default_session.collections # returns the collections

I usually extract the names as follows:

Mongoid.default_session.collections.map(&:name).sort
查看更多
登录 后发表回答