如何使用Python将JSON文件导入到MongoDB中

10 浏览
0 Comments

如何使用Python将JSON文件导入到MongoDB中

我有一个名为的JSON文件:\n{\n \"AUD\": 1.5978,\n \"BGN\": 1.9558,\n \"BRL\": 4.0726,\n \"CAD\": 1.5868,\n \"CHF\": 1.1703,\n \"CNY\": 7.7975,\n \"CZK\": 25.405,\n \"DKK\": 7.4478,\n \"GBP\": 0.87285,\n \"HKD\": 9.6889,\n \"HRK\": 7.4398,\n \"HUF\": 312.9,\n \"IDR\": 16993.0,\n \"ILS\": 4.2984,\n \"INR\": 80.255,\n \"ISK\": 122.1,\n \"JPY\": 129.74,\n \"KRW\": 1330.3,\n \"MXN\": 22.88,\n \"MYR\": 4.8365,\n \"NOK\": 9.5715,\n \"NZD\": 1.7024,\n \"PHP\": 64.64,\n \"PLN\": 4.2262,\n \"RON\": 4.663,\n \"RUB\": 70.539,\n \"SEK\": 10.194,\n \"SGD\": 1.6216,\n \"THB\": 38.495,\n \"TRY\": 4.888,\n \"USD\": 1.2346,\n \"ZAR\": 14.52\n}\n还有Python的连接如下:\nfrom pymongo import MongoClient\nclient = MongoClient(\'localhost\', 27017)\ndb = client[\'countries_db\']\ncollection_currency = db[\'currency\']\n我的数据库名是,具有集合。\n有没有办法使用将文件导入数据库?\n感谢您的帮助。

0
0 Comments

问题的出现原因:

根据问题中提供的代码,使用pymongo库中的insert_one、insert和insert_many方法来将JSON文件导入到MongoDB中。然而,执行完代码后,用户在MongoDB Compass中无法看到记录,只能通过执行db.collection.count()函数来查看正确数量的文档。用户在提问中提到,如果手动导入JSON文件,则可以在MongoDB Compass中看到文档。

问题的解决方法:

根据回答中提到的,如果要导入大文件,最好使用mongoimport和python的subprocess.run()方法。这种方法可以并行或同时导入多个JSON文件。

根据提问中的问题链接,可以找到更多关于如何同时导入多个JSON文件的解决方法。

整理后的文章如下:

如何使用Python将JSON文件导入到MongoDB

您可以使用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和python的subprocess.run()方法,就像这个问题中提到的那样。

如果您想一次插入多个JSON文件,可以参考这个问题链接中的解决方法。

希望这些信息对您有所帮助!

0