通过 Python 脚本将整个目录中的 JSON 文件导入到 MongoDB

Import JSON Files from an entire directory into a MongoDB via a Python script

我想通过 python 脚本将一个包含多个子目录和大量 JSON 文件的目录导入到 MongoDB 中。但是,我只能通过 GUI 在 Compass 中导入多个 JSON 或使用脚本一次导入一个文件,使用我从 Whosebug 的另一个问题中收集的以下代码():

import json 
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db=client['acme']
collection_posts = db ['posts']
with open('9995-f0763044.json') as f:
    file_data = json.load(f)
collection_posts.insert_one(file_data)
client.close()

如何更改此设置以便遍历整个目录并导入所有 JSON 文件?我已经看到了 insert_many() 方法,但据我所知,特定的文件名仍然需要写入代码。在我的完美场景中,我只需在脚本中输入一个目录,它就会扫描并上传该目录中的所有 JSON 文件。这可能吗?感谢您的帮助

是这样的吗?

import glob
filelist = glob.glob('your/path/*.json')
for filename in filelist:
    with open(filename) as f:
        file_data = json.load(f)
    collection_posts.insert_one(file_data)
client.close()