Created
September 20, 2012 07:56
-
-
Save jiren/3754527 to your computer and use it in GitHub Desktop.
Mongodb collection copier using moped gem
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 'moped' | |
class MongoCopier | |
attr_accessor :source_addr, :dest_addr, :db_name | |
attr_reader :source_session, :dest_session | |
def initialize(db_name, addrs = {}) | |
@source_addr = addrs[:source] || 'localhost:27017' | |
@dest_addr = addrs[:dest] || 'localhost:27017' | |
@db_name = db_name | |
end | |
def session(db_name, addr = 'localhost:27017') | |
s = Moped::Session.new([addr]) | |
s.use db_name | |
s.with(safe: { w: 2, wtimeout: 10 }) | |
return s | |
end | |
def copy_collection(colletion, query = {}) | |
source = self.session(db_name, source_addr) | |
dest = self.session(db_name, dest_addr) | |
source[colletion].find(query).each do |record| | |
dest[colletion].insert(record) | |
end | |
end | |
end | |
#Examples | |
copier = MongoCopier.new(:test, {source: "192.168.1.100:27017", dest: 'localhost:27017'}) | |
#copy full collection | |
copier.copy_collection(:products) | |
#copy selected record from the collection by passing query | |
copier.copy_collection(:products, {:name => 'iphone5'}) | |
copier.copy_collection(:products, {:categories => { '$in' => ['mobile', 'book']}}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment