PyMongo - 从另一台服务器克隆收集

时间:2014-03-21 21:23:12

标签: python mongodb pymongo

我试图使用Python将远程服务器上的集合克隆到带有索引的localhost(因为我以后必须使用Python自动执行多个任务)。从我所读过的内容来看,使用db.command是解决这个问题的最好方法,但我似乎无法让它发挥作用,甚至找不到我真正做错的事情。 #39;我的代码和错误,感谢任何帮助。

client = MongoClient()
db = clientProd.tools
colc = db.newDump

db.command({"cloneCollection": "databaseName.dump", "from": "example.com:6001"})

错误:

Traceback (most recent call last):
  File "/Users/dustin/Git/redbull_dev/test.py", line 14, in <module>
    dbProd.command({"cloneCollection": "databaseName.dump", "from": "example.com:6001"})
  File "/Library/Python/2.7/site-packages/pymongo-2.6.3-py2.7-macosx-10.8-intel.egg/pymongo/database.py", line 396, in command
  File "/Library/Python/2.7/site-packages/pymongo-2.6.3-py2.7-macosx-10.8-intel.egg/pymongo/helpers.py", line 147, in _check_command_response
pymongo.errors.OperationFailure: command {'from': 'example.com:6001', 'cloneCollection': 'databaseName.dump'} failed: no such cmd: from
[Finished in 5.2s with exit code 1]

2 个答案:

答案 0 :(得分:3)

显然你看过mongo的文档,你应该看看来自pymongo的文档http://api.mongodb.org/python/current/api/pymongo/database.html

从那以后,正确的命令应该是:

db.command("cloneCollection", collection="databaseName.dump", from="example.com:6001")

修改

由于from是python关键字,我们可能需要创建一个dict并解压缩它:

db.command("cloneCollection", **{'collection': "databaseName.dump", 'from': "example.com:6001"})

答案 1 :(得分:1)

我发现所选择的解决方案不太起作用(可能是版本问题),这是我的解决方案:

db_dest.command("cloneCollection", **{"cloneCollection": db_str + ".Sentence",
                                              'collection': db_str + ".Sentence",
                                              'from': mongodb_ip + ":27017"})