python - MongoDB 和 PyMongo - 类似 SQL 的列

标签 python sql mongodb pymongo

我有一个 MySQL 数据库,其中有一个名为 sources 的表,其中有两列名为 srctypeurl 其中 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/

相关文章:

python - pylons mongoengine 类型对象 'Section' 没有属性 _data

node.js - ObjectID 显示 Unicode 乱码而不是字符串

javascript - 如何让nodejs与golang对话

python - 如何有效地将 Pandas Dataframe 保存到一个/多个 TFRecord 文件中?

python:如何将 'unicodedata' 模块添加到我当前的 python 库

mysql - 酒店日期过滤器 : return only hotels that respect minimum stay period specified for range (SQL or Elasticsearch)

mysql - 如何在 MySQL 列中查找相同值的最高计数

java - SQL 数据库和 Java

python - 具有特定列聚合功能的 Pandas df.resample

python - DRY 选择字典的子集