我有一个 MySQL 数据库,其中有一个名为 sources 的表,其中有两列名为 srctype 和url 其中 srctype 是名称(例如:Hello),url 是 url(例如: http://google.com )
例如,在使用 SQLAlchemy 的 Python 中,我可以过滤 srctype 并获取 url 列表;
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 函数中,我简单地向 MongoDB 添加一个 dict ,显然我无法在 getSources 函数中获取 srctype,因为 MongoDB 中的 srctype 不是列。 任何帮助都会很棒。
最佳答案
您的问题是保存数据时没有正确设置名称。而不是
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}
。
关于python - MongoDB 和 PyMongo - 类似 SQL 的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13203294/