首页 > 解决方案 > How to create collections dynamically and insert json file's data in to each of them

问题描述

On ref SO suggestions , I tried inserting a bunch of Json files data to single collection as :

import json
import pymongo
client = pymongo.MongoClient('mongodb+srv://********:*******@cluster0-kb3os.mongodb.net/test?retryWrites=true&w=majority')
db = client['mydb']
test = db['test']

Then I have the json files as a.json,b.json,....,z.json , to insert all these to a single collection, I did this way as:

file_names = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
json_file_names=[x + '.json' for x in file_names]

for file_name in json_file_names:
    with open(file_name,encoding="utf8") as f:
        file_data = json.load(f)
        for word in file_data:
            word_obj = file_data[word]
            test.insert_one(word_obj)

When querying the results which is referring to particular letter record,I guess it is good to have the separate collection which might increase performance too instead of searching whole collection.

I have been looking on how to create collections dynamically such that each collection say a_col has a.json data inserted,b_col has b.json, ........

Is there a way to create as this ? , any guiding links or snippets as answer would be much helpful , TIA

标签: pythonpymongo

解决方案


在读取每个文件后,在您的 for 循环中根据您的文件名更改集合名称。就像test = db[filename]每次插入数据之前都会创建一个新集合一样。


推荐阅读