How do I copy a collection from one database to another database on the same server using PyMongo?

你说的曾经没有我的故事 提交于 2019-12-09 04:21:28
snth

After a lot of confusion and soul searching, I was eventually able to track this down to dicts in Python being unordered (at least prior to 3.6) and MongoDB expecting an ordered BSON dictionary.

Using an OrderedDict as pointed out in How to get ordered dictionaries in pymongo? resolve this:

>>> from collections import OrderedDict
>>> client.admin.command(
    OrderedDict([('renameCollection','db1.coll2'), ('to','db2.coll2')]))
{u'ok': 1.0}

Another alternative is to use a SON object from BSON.

>>> import bson
>>> client.admin.command(
    bson.son.SON([('renameCollection','db1.coll2'), ('to','db2.coll2')]))
{u'ok': 1.0}

Another approach is to pass Javascript to MongoDB using the eval() function:

>>> client.admin.eval(
    "db.runCommand({'renameCollection':'db1.coll2', 'to':'db2.coll2'})") 
{u'ok': 1.0}

I find the raw Javascript version less pythonic but is useful because it allowed me to test the MongoDB functionality without having to fire up a MongoDB shell. I also haven't seen it mentioned much on PyMongo StackOverflow questions so thought it's worth including here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!