1

我正在尝试从 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 集合,而是创建一个同名的空数据库。无法弄清楚我做错了什么。有任何想法吗?谢谢!

4

2 回答 2

2

以下 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(' ')}")

如果您有任何其他问题,请告诉我。

于 2013-01-03T17:40:54.997 回答
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实现。

于 2014-11-11T17:52:37.493 回答