【问题标题】:How to import JSON file to MongoDB using Python如何使用 Python 将 JSON 文件导入 MongoDB
【发布时间】:2018-09-05 16:40:58
【问题描述】:

我有这个 JSON 文件,currencies.json:

{
    "AUD": 1.5978,
    "BGN": 1.9558,
    "BRL": 4.0726,
    "CAD": 1.5868,
    "CHF": 1.1703,
    "CNY": 7.7975,
    "CZK": 25.405,
    "DKK": 7.4478,
    "GBP": 0.87285,
    "HKD": 9.6889,
    "HRK": 7.4398,
    "HUF": 312.9,
    "IDR": 16993.0,
    "ILS": 4.2984,
    "INR": 80.255,
    "ISK": 122.1,
    "JPY": 129.74,
    "KRW": 1330.3,
    "MXN": 22.88,
    "MYR": 4.8365,
    "NOK": 9.5715,
    "NZD": 1.7024,
    "PHP": 64.64,
    "PLN": 4.2262,
    "RON": 4.663,
    "RUB": 70.539,
    "SEK": 10.194,
    "SGD": 1.6216,
    "THB": 38.495,
    "TRY": 4.888,
    "USD": 1.2346,
    "ZAR": 14.52
}

Python 中的这种连接:

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client['countries_db']
collection_currency = db['currency']

我的数据库名称是 countries_dbcurrency 集合。 有没有办法使用python 将文件导入数据库?
感谢您的帮助。

【问题讨论】:

    标签: python json python-3.x mongodb


    【解决方案1】:

    您可以使用insert_one 方法从文件中读取数据并将其插入到集合中:

    import json
    from pymongo import MongoClient
    
    client = MongoClient('localhost', 27017)
    db = client['countries_db']
    collection_currency = db['currency']
    
    with open('currencies.json') as f:
        file_data = json.load(f)
    
    # if pymongo < 3.0, use insert()
    collection_currency.insert(file_data)
    # if pymongo >= 3.0 use insert_one() for inserting one document
    collection_currency.insert_one(file_data)
    # if pymongo >= 3.0 use insert_many() for inserting many documents
    collection_currency.insert_many(file_data)
    
    client.close()
    

    【讨论】:

    • 如果你有一个大文件,你可能会更好地使用mongoimport,就像this question和python的subprocess.run()一样
    • 请问如何一次插入多个json文件?
    • @Codenewbie 嗨)你所说的“一次”是什么意思?在平行下?同时?还是只是一大批?
    • 看看答案
    • @jtlz2 固定,ty)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-25
    • 2018-12-25
    • 2015-10-13
    • 1970-01-01
    • 2019-07-10
    • 2014-12-24
    相关资源
    最近更新 更多