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

Software Compatibility Best Practices

I spoke to some of the most talented and experienced software developers. I have created a guide that is filled with valuable insights and actionable ideas to boost developer productivity.

You will gain a better understanding of what's working well for other developers and how they address the software compatibility problems.

Get the Guide Now