我试图从ruby调用mongodb cloneCollection命令。基于https://github.com/mongodb/mongo-ruby-driver/wiki/FAQ的第一个问题,我制作了这个测试脚本:
require "mongo"
include Mongo
db = MongoClient.new("localhost", 27017).db("test")
coll = "users2"
cmd = {}
cmd['cloneCollection'] = coll
cmd['from'] = "test.example.com:27017"
db.command(cmd)
但是,它不是克隆users2集合,而是创建一个具有相同名称的空数据库。无法弄清楚我做错了什么。有任何想法吗?谢谢!
答案 0 :(得分:2)
以下Ruby程序是一个独立的工作示例,可以回答您的问题,完成源和目标mongod服务器的启动。
似乎cloneCollection的arg必须是完全限定的名称,例如“test”用于“test”数据库中的“users”集合。
require "mongo"
# startup source and destination mongod servers
source = { 'port' => 27018, 'dbpath' => 'data27018' }
dest = { 'port' => 27019, 'dbpath' => 'data27019' }
[ source, dest ].each do |server|
dbpath = server['dbpath']
system("rm -fr #{dbpath} && mkdir #{dbpath} && mongod --port #{server['port']} --dbpath #{dbpath} &")
end
sleep 10 # delay for mongod startup
db_name = 'test'
coll_name = 'users'
db_coll_name = "#{db_name}.#{coll_name}"
# create source collection
db = Mongo::MongoClient.new("localhost", source['port']).db(db_name)
coll = db[coll_name]
coll.insert({'name' => 'Gary'})
# cloneCollection from source to dest
db = Mongo::MongoClient.new("localhost", dest['port']).db(db_name)
cmd = BSON::OrderedHash.new
cmd['cloneCollection'] = db_coll_name
cmd['from'] = "localhost:#{source['port']}"
db.command(cmd)
# verify cloneCollection
p db[coll_name].find.to_a
# kill mongod servers
pids = `pgrep mongod`.split(/\n/).sort.slice(-2,2)
system("kill #{pids.join(' ')}")
如果您有任何其他问题,请与我们联系。
答案 1 :(得分:0)
感到惊讶的是Mongo::DB
没有cloneCollection
方法,并且阅读上面的@Gary Murakami的优秀答案,我写了这片猴子补丁,但我对它有用其它:
class Mongo::DB
def cloneCollection(remote_host, collection_name)
cmd = BSON::OrderedHash.new
cmd['cloneCollection'] = name + "." + collection_name
cmd['from'] = remote_host
self.command(cmd)
end
end
只需将其放在源文件中的任意位置即可获得Mongo::DB.cloneCollection
实施。