将python列表插入到mongodb中?

时间:2019-07-19 11:32:44

标签: python mongodb

我想在mongodb数据中插入一个python列表。我将如何插入? 下面是我的代码。错误是

  

列表没有to_dict的方法

代码如下:

from pymongo import MongoClient
client = MongoClient()
db = client.espace
espace = db.espacedata
records = a.to_dict(orient = 'records')
data = ['AGRICULTURE\n A01\nAGRICULTURE; FORESTRY; ANIMAL HUSBANDRY; HUNTING; TRAPPING; FISHING', ' A01\nAGRICULTURE; FORESTRY; ANIMAL HUSBANDRY; HUNTING; TRAPPING; FISHING', "FOODSTUFFS; TOBACCO\n A21\']
records = data.to_dict(orient = 'records')
results = espace.insert_many(records)

2 个答案:

答案 0 :(得分:0)

您可以只使用一个将记录作为值的字典,您可以这样做:

espace.insert_many([{'records':data}]) 
# or
escape.insert_one({'records': data})

答案 1 :(得分:0)

首先,data中的语法存在问题。最终由于引号\'的转义而无法解析。您需要添加一个封闭的单引号,如下所示。

data = ['AGRICULTURE\n A01\nAGRICULTURE; FORESTRY; ANIMAL HUSBANDRY; HUNTING; TRAPPING;
FISHING', ' A01\nAGRICULTURE; FORESTRY; ANIMAL HUSBANDRY; HUNTING; TRAPPING; FISHING',  
'FOODSTUFFS; TOBACCO\n A21\'']

如果您尝试使用pandas,请使用以下或上面给出的方法:

data = ['AGRICULTURE\n A01\nAGRICULTURE; FORESTRY; ANIMAL HUSBANDRY; HUNTING; TRAPPING; FISHING', ' A01\nAGRICULTURE; FORESTRY; ANIMAL HUSBANDRY; HUNTING; TRAPPING; FISHING', 'FOODSTUFFS; TOBACCO\n A21\'']

df = pd.DataFrame(data)
records = df.to_dict()
print(records)

否则,如@rusu所建议,将direct用作:

espace.insert_many([{'records':data}])