【问题标题】:How do I import json file using pymongo?如何使用 pymongo 导入 json 文件?
【发布时间】:2019-04-17 00:01:09
【问题描述】:
我尝试使用它,但它不起作用。
from pymongo import MongoClient
import json
client = MongoClient('localhost', 27017)
client('mongoimport --db myDatabase --collection restaurants --file c:\restaurants\restaurants.json')
print ('json import sucessfully')
非常感谢任何帮助。谢谢
【问题讨论】:
标签:
json
file
import
pymongo
【解决方案1】:
类似于answer,mongoimport 是一个命令行程序,不在 PyMongo API 中。
但是您可以使用不同的方法:
from pymongo import MongoClient
import json
client = MongoClient('localhost', 27017)
with open('restaurants.json') as f:
data = json.load(f)
client['myDatabase']['restaurants'].insert_many(data)
如果您的 json 文件太大,您可以使用 subprocess lib 在 python 程序中运行命令行程序。检查一些 SO 答案 here 或 here