python - 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
解决方案
在读取每个文件后,在您的 for 循环中根据您的文件名更改集合名称。就像test = db[filename]
每次插入数据之前都会创建一个新集合一样。
推荐阅读
- ios - 代码点火器 - 无法连接:0 发送 ios 通知时
- mysql - 无法在 phpmyadmin - mysql 中添加外键约束
- regex - Regexp_like 与在线正则表达式验证器 - 不同的结果
- swift - 在 indexPath.row 的数组中快速打印元素
- c# - 如何在 Unity 中使用 C# 生成随机浮点数(Unity 拒绝大多数其他建议的答案)?
- react-native - 更新坐标数组时不呈现多条折线
- django - Django 忽略模型字段
- python - Python 数组和矩阵
- xcode - 在 Xcode 中错误地删除了整个项目的引用
- android - 如何从 sqlite 检索数据到 ListView