Looking for a way to shard a MongoDB collection from within Python code

mongodb, pymongo, python, python-2.7, sharding

Solution

Follow the instructions for setting up a sharded cluster, up to the point where you connect the "mongo" shell to the mongos server and say:

sh.enableSharding("<database>")

Instead, view the code for `enableSharding` by just typing the command without parentheses:

sh.enableSharding

You can see that it executes `{ enableSharding : dbname }` on the "admin" DB, so do that with pymongo:

client = pymongo.MongoClient()
client.admin.command('enableSharding', 'dbname')

Replace 'dbname' with your database name, obviously. Repeat to shard a collection. Get the code from the shell:

sh.shardCollection

And execute the same command in Python:

client.admin.command('shardCollection', 'dbname.collectionname', key={'shardkey': 1})

Problem

I'm searching for a way to remotely perform sharding on an existing collection, from within a python (2.7) program. I wasn't able to find an API that performs that (pymongo), or maybe just wasn't looking good enough. Is such thing possible? Thanks in advance

Original source