Skip to content

Instantly share code, notes, and snippets.

@we4tech
Last active December 11, 2015 05:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save we4tech/4554308 to your computer and use it in GitHub Desktop.
Save we4tech/4554308 to your computer and use it in GitHub Desktop.
Export mongodb collections and their properties to HTML format
# Export collection name and their properties list in HTML format.
require 'mongo'
include Mongo
# Connect with mongodb server
client = MongoClient.new('localhost', 27017)
# Load database
db = client['YOUR DB NAME']
# List all excluded collections
excluded_collections = ['system.indexes']
# Genearte new html
html = %{<html>
<head><title>Collection properties</title>
<style>
h4 { background: #f0f0f0; padding: 5px; display: block; border-bottom: 1px solid #ccc; margin-bottom: 2px; }
table { border: 1px solid #ccc; width: 100%; }
table tr td { border-bottom: 1px solid #ccc; }
table tr th { background: #f0f0f0; border-bottom: 1px solid #ccc; }
h1 { background: #f0f0f0; padding: 5px; border-bottom: 2px solid #ccc; }
</style>
</head>
<body>
<h1>Collections from #{db.name}</h1>
}
html << '<table>'
# Iterate through all collections and retrieve their all keys
# based on first record.
db.collection_names.each do |n|
# Don't add collection if it doesn't contain any record
if !db[n].find_one.nil? && !excluded_collections.include?(n)
html << "<tr><th colspan='2'><h4>Collection: #{n}</h4></th></tr>"
html << '<tr><th>Column</th><th>Type</th>'
html << db[n].find_one.map{|k, v| "<tr><td>#{k}</td><td>#{v.class.name}</td></tr>"}.join
end
end
html << '</table>'
html << '</body>'
# Write this html to some location
File.open('YOUR PATH to OUTPUT', 'wb') {|f| f.puts html }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment