Skip to content

Instantly share code, notes, and snippets.

@kenbod
Last active August 29, 2015 14:15
Show Gist options
  • Save kenbod/ce7c97ee0ca2066d796e to your computer and use it in GitHub Desktop.
Save kenbod/ce7c97ee0ca2066d796e to your computer and use it in GitHub Desktop.
Store shell script in MongoDB
require 'bundler/setup'
require 'json'
require 'mongo'
require 'fileutils'
include Mongo
if __FILE__ == $0
# establish a connection to MongoDB
mongo = MongoClient.new
# access the "scripts" collection of the "shell_script_test" db
db = mongo.db("shell_script_test")
scripts = db['scripts']
# search for a document whose name is 'neo4j'
doc = scripts.find_one(name: 'neo4j')
# write the contents of the script to a copy of the original script
output_file = File.open("neo4j_copy", "w")
output_file.print doc["contents"]
output_file.close
# since we started with an executable script; make the copy executable too
FileUtils.chmod "u+x", 'neo4j_copy'
# all done
mongo.close
end
require 'bundler/setup'
require 'json'
require 'mongo'
include Mongo
if __FILE__ == $0
# assume 'neo4j' script is present in current directory; read it into memory
input_file = File.open('neo4j');
contents = input_file.read
# create a Hash with the name of the shell script and its contents
document = { name: 'neo4j', contents: contents }
# establish a connection to MongoDB
mongo = MongoClient.new
# access the "shell_script_test" db; note: creates db if not present
db = mongo.db("shell_script_test")
# access the 'scripts' collection within the db; note: creates it if not present
scripts = db['scripts']
# insert the script into the collection
scripts.insert( document );
# all done
mongo.close
end

Storing Files in MongoDB

Here's a quick, two-script example of storing and retrieving the contents of a file in MongoDB.

import_script.rb: reads a file and stores it in MongoDB. Hardwired to use the 'neo4j' start-up script. You can change the name to be anything you want (just update the name that is stored in the 'document' variable too!).

get_script.rb: reads a file from MongoDB and writes it to the file system. Again, this example is hardwired to work with the neo4j script that was used in the import_script.rb file. You can once again update this code to work with any script that you have on your own computer.

These programs are written in Ruby and make use of the 'mongo' gem to access MongoDB.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment