Created
March 22, 2013 04:34
-
-
Save tfanme/5218958 to your computer and use it in GitHub Desktop.
export data from SQL Server to MongoDB using Ruby and Rails
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 "rubygems" | |
| require "active_record" | |
| require "mongo" | |
| include Mongo | |
| # 声明一个 MongoDB client | |
| @client = MongoClient.new('localhost', 27017) | |
| # MongoDB db | |
| @db = @client['your_mongo_dbname'] | |
| # MongoDB collection | |
| @coll = @db['your_collection_name'] | |
| @coll.remove | |
| # 连接 SQL Server 数据库的设置 | |
| ActiveRecord::Base.establish_connection( | |
| :adapter => "sqlserver", | |
| :host => "your_database_ipaddress", | |
| :database => "your_database_name", | |
| :username => "your_database_username", | |
| :password => "your_database_password" | |
| ) | |
| class FooBar < ActiveRecord::Base | |
| # 指定我们实际的表的名字 | |
| self.table_name = "your_table_name" | |
| end | |
| # 使用 find_each 遍历我们的大数据量表 | |
| FooBar.find_each(:batch_size => 1000) do |foo| | |
| # 插入到 MongoDB 的 collection 中 | |
| @coll.insert({'col1' => "#{foo.bar1}", "col2" => "#{foo.bar2}", "col3" => "#{foo.bar3}"}); | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment