如何使用BSON(Python)从MongoDB检索存储的数据?

2024-06-16 12:08:18 发布

您现在位置:Python中文网/ 问答频道 /正文

到目前为止,在我的代码中,我设法将数据存储到mongoDB中。 现在我希望能够检索我存储的数据。 正如你所看到的,我一直在努力,但不断地出错。 使用BSON,我必须首先解码数据才能从mongoDB检索数据吗? 任何帮助都将不胜感激! (为混乱的代码道歉,我只是通过尝试和错误练习)

import json
from json import JSONEncoder

import pymongo 
from pymongo import MongoClient

from bson.binary import Binary
import 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 

Tags: 数据fromimportselfjsondbcollectionperson
1条回答
网友
1楼 · 发布于 2024-06-16 12:08:18

应该对集合调用find_one方法

{'bin-data': Binary(practicedata)}是查找文档的查询

coll.find_one({'bin-data': Binary(practicedata)})

Witch的意思是:在集合coll中查找一个文档,其中bin-data等于Binary(practicedata)

相关问题 更多 >