Question

I am attempting to use pymongo to clone a collection from a remote mongo instance, from the documentation cloning a collection requires the cloneCollection command,

{ cloneCollection: "<collection>", from: "<hostname>", query: { <query> } }

and to run this command in pymongo I need to specify the additional parameters of the command as kwargs like this:

db.command("cloneCollection","db_name.collection_name", from = "localhost:27017")

But since from is a reserved keyword in python I cannot use it as a keyword. An alternative is to pass the command as a python dict like this:

db.command({"cloneCollection":"db_name.collection_name", "from":"localhost:27017"})

However in this case the order is not preserved, and I get this error

pymongo.errors.OperationFailure: command {'from': 'localhost:27017', 'cloneCollection': 'db_name.collection_name'} failed: no such cmd: from
Était-ce utile?

La solution

Depending on how pymongo uses the dictionary, you might be able to use OrderedDict (from the builtin collections module). This is only available from python 2.7, but there are backports available for python 2.4 onwards.

In this case you could do something like:

from collections import OrderedDict
config = OrderedDict((
    ("cloneCollection", "db_name.collection_name"),
    ("from", "localhost:27017"),
))
db.command(config)

Autres conseils

Figured that I can use bson.son.SON to create a SON object (a subclass of dict that maintains ordering of keys), pymongo also does this internally when we pass arguments or python dict to pymongo commands,

from bson.son import SON
db.command(SON([("cloneCollection","db_name.collection_name"), ("from","localhost:27017")]))
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top