Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 859
Meny Issakov Avatar asked Dec 11 '22 07:12

Meny Issakov


1 Answers

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})
like image 148
A. Jesse Jiryu Davis Avatar answered Apr 06 '23 05:04

A. Jesse Jiryu Davis