from pymongo import MongoClient, HASHED
paper_names = ["table_name"]
client = MongoClient('xx.xx.xx.xx', 27017, username="admin", password="123456")
for paper_name in paper_names:
paper_db = client["Collection_name"]
paper_col = paper_db[paper_name]
paper_index_info = paper_col.index_information()
print(paper_index_info)
if "_id_hashed" not in paper_index_info.keys():
print(paper_name)
paper_col.create_index([("_id", HASHED)])
client.admin.command("shardCollection", f"{paper_db.name}.{paper_name}", key={"_id": "hashed"})
{'_id_': {'v': 2, 'key': [('_id', 1)], 'ns': 'table_name.Collection_name'}, '_id_hashed': {'v': 2, 'key': [('_id', 'hashed')], 'ns': 'table_name.Collection_name'}