简体   繁体   English

TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, 继承自 collections.MutableMapping 的类型

[英]TypeError: document must be an instance of dict, bson.son.SON, bson.raw_bson.RawBSONDocument, a type that inherits from collections.MutableMapping

I am trying to write data into pymongo and this the TypeError that I am getting.我正在尝试将数据写入pymongo ,这是我得到的 TypeError。 The Type for mydict1 is List . mydict1的类型是List Do I have to convert my data into json or bson before I write it to pymongo ?在将数据写入pymongo之前,是否必须将数据转换为jsonbson Kindly help.请帮忙。 Thanks.谢谢。

from numpy.polynomial import Polynomial as poly 
import numpy as np
import matplotlib.pyplot as plt
import pymongo
import json
import pandas as pd

 
df = pd.read_csv(r'D:\polynomial\points.csv')
print(df)

x= np.array(df['Wavelength(A)'].tolist())
x= np.divide([299792.458], x)
y= np.array(df['Level(A)'].tolist())
x_trimmed = np.delete(x, np.where(y < 1e-4))
y_trimmed = np.delete(y, np.where(y < 1e-4))
test= poly.fit(x_trimmed, y_trimmed, 10)
print (test)

list1= test.convert().coef
print (list1)
print (len(list1))
#print (type(list1))
to_list= list1.tolist()
#print(to_list)
#data_format= json.dumps(to_list)
l = len(to_list)
#print (l)
mydict1= []
for i in range(l):
    mydict = { "a"+str(i) : to_list[i] }
    mydict1.append(mydict)
print (mydict1)


myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["coefficients"]
x = mycol.insert_one(mydict1)

This is mydict1=这是 mydict1=

[{'a0': -2.3373800910827825e+34}, {'a1': 1.2084654060419298e+33}, {'a2': -2.811587585787653e+31}, {'a3': 3.876370042231405e+29}, {'a4': -3.507261557232249e+27}, {'a5': 2.1759768836934694e+25}, {'a6': -9.37514311649608e+22}, {'a7': 2.7697765301392782e+20}, {'a8': -5.370081422614614e+17}, {'a9': 616983041924503.2}, {'a10': -318990754999.1472}]

The problem is that MongoDB's insert_one method inserts a single document that is represented by a dictionary, not a list.问题是 MongoDB 的insert_one方法插入了一个由字典表示的单个文档,而不是列表。

The possible solutions are:可能的解决方案是:

  • use insert_many instead.改用insert_many In this case, you will have every list item as a separate mongodb document在这种情况下,您会将每个列表项作为单独的 mongodb 文档
  • make a dict with your list values.用您的列表值制作一个字典。 You can use something like {"items": mydict1} , or reduce(lambda x, y: x | y, mydict1) depending on the document structure that will be better for your needs您可以使用类似{"items": mydict1}reduce(lambda x, y: x | y, mydict1)的内容,具体取决于更适合您需要的文档结构

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM