【问题标题】:Import JSON Files from an entire directory into a MongoDB via a Python script通过 Python 脚本将整个目录中的 JSON 文件导入 MongoDB
【发布时间】:2021-08-30 07:10:15
【问题描述】:

我想通过 python 脚本将具有多个子目录和大量 JSON 文件的目录导入 MongoDB。但是,我只能通过 Compass 中的 GUI 导入多个 JSON,或者使用脚本一次使用一个文件导入多个 JSON,该脚本使用我从 stackoverflow(How to import JSON file to MongoDB using Python)的另一个问题收集的以下代码:

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 文件。这甚至可能吗?感谢您的帮助

【问题讨论】:

    标签: python json mongodb automation directory


    【解决方案1】:

    这样的?

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-03
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2013-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多