如何使用Python将JSON文件导入到MongoDB中
如何使用Python将JSON文件导入到MongoDB中
我有一个名为
问题的出现原因:
根据问题中提供的代码,使用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文件,可以参考这个问题链接中的解决方法。
希望这些信息对您有所帮助!