我有一个MySQL数据库,其中包含一个名为 sources 的表,我有两列名为 srctype , url 其中srctype是一个名称(例如:Hello),而url是一个网址(例如:http://google.com)
在使用SQLAlchemy的Python中,我可以过滤srctype并获取网址列表,例如;
src = "hello"
links = session.query(sources).filter_by(srctype=src).all()
很简单,现在我将这些数据迁移到MongoDB,为此我使用 pymongo 。
我有一个函数,它将srctype和url保存到mongodb的数据库
def insertSources(self, srctype, link):
""" Insert rss sources so we can parse them """
new = {srctype: link}
self.__sources.insert(new)
和一个检索srctype
的函数 def getSources(self, type=None, single=True): # type == srctype
if type:
if single:
return self.__sources.find_one()
else:
return iter(self.__sources.find({srctype:type}))
else:
if single:
return self.__sources.find_one()
else:
return iter(self.__sources.find())
这里的问题是,由于没有名为srctype的列,也没有名为url的列,我该怎样做与SQLAlchemy / MySQL示例相同?
在MySQL中会是;
SELECT * FROM sources WHERE srctype="hello"
我想知道在我的检索功能中会有多少(也在插入功能中,因为我不确定我所做的是否对我想要的工作是正确的)。在 insertSources 函数中,我简单地将一个 dict 添加到MongoDB中,显然我无法在getSources函数中获取srctype,因为MongoDB中的srctype不是列。 任何帮助都会很棒。
答案 0 :(得分:2)
您的问题是您在保存数据时没有正确设置名称。而不是
def insertSources(self, srctype, link):
""" Insert rss sources so we can parse them """
new = {srctype: link}
self.__sources.insert(new)
你应该做
def insertSources(self, srctype, link):
""" Insert rss sources so we can parse them """
new = {'srctype': srctype, 'link': link}
self.__sources.insert(new)
同样在getSources()
中。如果srctype
通过,find()
和find_one()
应该会收到{'srctype': type}
。