到目前为止,在我的代码中,我成功地将数据存储到 mongoDB 中。现在我希望能够检索我存储的数据。正如你所看到的,我一直在尝试,但不断出现错误。使用 BSON 时,我是否必须首先解码数据才能从 mongoDB 检索数据?任何帮助将不胜感激!(对混乱的代码表示歉意,我只是通过反复试验进行练习)import jsonfrom json import JSONEncoderimport pymongo from pymongo import MongoClientfrom bson.binary import Binaryimport pickle#Do this for each client = MongoClient("localhost", 27017)db = client['datacampdb']coll = db.personpractice4_collection #creating a collection in the database #my collection on the database is called personpractice4_collection class Person: def __init__(self, norwegian, dame, brit, german, sweed): self.__norwegian = norwegian self.__dame = dame self.__brit = brit self.__german = german #private variable self.__sweed = sweed # create getters and setters later to make OOP personone = Person("norwegian", "dame", "brit", "german","sweed") class PersonpracticeEncoder(JSONEncoder): def default(self, o): return o.__dict__ #Encode Person Object into JSON"personpracticeJson = json.dumps(personone, indent=4, cls=PersonpracticeEncoder)practicedata = pickle.dumps(personpracticeJson)coll.insert_one({'bin-data': Binary(practicedata)})#print(personpracticeJson)#print(db.list_collection_names()) #get then names of my collections in DB #retriving data from mongodb #Retrieving a Single Document with find_one()print(({'bin-data': Binary(practicedata)}).find_one()) #not working
1 回答
红糖糍粑
TA贡献1815条经验 获得超6个赞
find_one
应该在集合上调用该方法
{'bin-data': Binary(practicedata)}
是查找文档的查询
coll.find_one({'bin-data': Binary(practicedata)})
女巫的意思是:在集合中查找一个文档coll
,其中bin-data
等于Binary(practicedata)
添加回答
举报
0/150
提交
取消