Skip to content

Instantly share code, notes, and snippets.

@ralic
Forked from Andrzej/bson2sql.rb
Created July 13, 2018 11:27
Show Gist options
  • Save ralic/c0a47be57ca5bd63b86f83837ad20b0f to your computer and use it in GitHub Desktop.
Save ralic/c0a47be57ca5bd63b86f83837ad20b0f to your computer and use it in GitHub Desktop.
Convert BSON file into SQL, useful for fast copy data from MongoDB to MySQL (mongodump => bson2sql => import to mysql)
require "bson"
def make_insert(table_name, bson)
columns = ["id",*bson["value"].keys] * ", "
values = ["'#{bson["_id"]}'",*bson["value"].values.map{|value| value.is_a?(Numeric) ? value : "'#{value}'"}] * ", "
return "insert into #{table_name} (#{columns}) values (#{values});"
end
file_name = ARGV.first
file=File.new(file_name)
table_name=File.basename(file_name,".*")
while not file.eof? do
bson = BSON.read_bson_document(file)
STDOUT << make_insert(table_name,bson)
STDOUT << "\n"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment