Last active
November 21, 2016 09:21
-
-
Save jamesmichiemo/fdd419c095d695d47a2d to your computer and use it in GitHub Desktop.
an example for syncing between mongodb and mysql databases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| require 'mongo' | |
| require 'mysql' | |
| include Mongo | |
| mongo_connection = MongoClient.new("localhost", 27017) | |
| itunes_db = mongo_connection.db("itunes") | |
| @collection = itunes_db["itunes"] | |
| @itunes_array = @collection.find("type" => "track").to_a | |
| @itunes_array.each do |record| | |
| begin | |
| mysql_db = Mysql.new('localhost', 'root', 'root', 'itunes') | |
| insert_track = mysql_db.prepare "insert into itunes (persistentid,album,artist,size,kind,year,playcount,lastmodified) values('#{record['PersistentID'].to_s.gsub("'","\\\\'")}','#{record['Album'].to_s.gsub("'","\\\\'")}','#{record['Artist'].to_s.gsub("'","\\\\'")}','#{record['Size']}','#{record['Kind'].to_s.gsub("'","\\\\'")}','#{record['Year']}','#{record['TrackCount']}','#{record['DateModified']}') on duplicate key update album=album, artist=artist, size=size, year=year, playcount=playcount, lastmodified=lastmodified;" | |
| insert_track.execute | |
| ensure | |
| mysql_db.close | |
| end | |
| end | |
| begin | |
| mysql_db = Mysql.new('localhost', 'root', 'root', 'itunes') | |
| all_itunes = mysql_db.query("SELECT * FROM itunes") | |
| all_itunes.each_hash do |row| | |
| @collection.save({PersistentID: "#{row['persistentid']}", Album: "#{row['album']}", Artist: "#{row['artist']}", Size: "#{row['size']}", Kind: "#{row['kind']}", Year: "#{row['year']}", TrackCount: "#{row['playcount']}", DateModified: "#{row['lastmodified']}"}) unless @itunes_array.any? { |record| record['PersistentID'] == row['persistentid'] } | |
| end | |
| ensure | |
| mysql_db.close | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi it updates all rows not delta updates so it is not really sync.