Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get list of mongodb databases and collections list from a ruby on rails app

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.

like image 328
user622773 Avatar asked Feb 28 '11 13:02

user622773


People also ask

How do I get a list of databases in MongoDB?

If you want to check your databases list, use the command show dbs. Your created database (mydb) is not present in list. To display database, you need to insert at least one document into it. In MongoDB default database is test.

How do I get a list of collection names in MongoDB?

To list all collections in Mongo shell, you can use the function getCollectionNames().

What is the command to show a list of all MongoDB databases?

Listing all the databases in mongoDB console is using the command show dbs .


2 Answers

In mongoid 3

Mongoid.default_session.collections # returns the collections

I usually extract the names as follows:

Mongoid.default_session.collections.map(&:name).sort
like image 181
Harish Shetty Avatar answered Oct 05 '22 11:10

Harish Shetty


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
like image 22
Steve Avatar answered Oct 05 '22 13:10

Steve