MongoDB Basics : List Collections and Documents


To learn how to list all collections and documents in a collection programmatically using Ruby.


Step 1

Create document.rb:

require 'mongo'

include Mongo

client =[ '' ], :database => 'blog_development')

collection = :articles
p client[collection].find.count

dn = client[collection].find

dn.each do |doc|
  puts doc

Step 2

require 'mongo'

include Mongo

client =[ '' ], :database => 'blog_development')
database = client.database

p database.collections #=> Returns an array of Collection objects.
p database.collection_names #=> Returns an array of collection names as strings.

Step 3

If you are using Mongoid gem, you can check the currently connected database:

puts "Connected to : #{Mongoid.default_session.options[:database]}"


In this article you learned how to list all collections in a given database and how to list all documents in a collection programmatically using mongo db Ruby driver.

Related Articles

Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.