以下 Ruby 程序是一个独立的工作示例,应该可以回答您的问题,并启动源和目标 mongod 服务器。
看来 cloneCollection 的 arg 必须是完全限定名称,例如,“test”数据库中“users”集合的“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(' ')}")
如果您有任何其他问题,请告诉我。