python - 如何使用 BSON (Python) 从 MongoDB 中检索存储的数据?
问题描述
到目前为止,在下面的代码中,我设法将数据存储到 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
解决方案
该find_one
方法应该在集合上调用
{'bin-data': Binary(practicedata)}
是查找文档的查询
coll.find_one({'bin-data': Binary(practicedata)})
女巫的意思是:在集合中找到一个文档,coll
其中bin-data
等于Binary(practicedata)
推荐阅读
- android - 如何在 Android 上使用可绘制的 xml 文件修复背景图像?
- r - 如何知道不同年份的年度变化/检查每年的平均值?
- python - 如何在 Pandas 列中拆分逗号分隔的单词列表?
- swift - 为什么我的 self.init 不会自动填充便利初始化程序?
- python - 如何将相同的值添加到字典中的不同键?
- java - 运行服务“Google Play 服务”使用大量 RAM
- r - 获取对 R 中的特定列具有相同值的所有行名
- java - 有没有办法在Java(类似LINQ)中创建另一个对象的集合?
- r - 如何使用 R 中的 ets() 或 holt() 函数复制 Excel 2016 forecast.ets 的结果?
- python - 有没有办法为本地文件生成 URL?