【问题标题】:querying mongodb using pymongo使用 pymongo 查询 mongodb
【发布时间】:2015-05-04 23:39:14
【问题描述】:

我刚开始使用 mongodb 并设置了一个测试数据库来处理我创建的几个脚本的网络抓取结果。现在, date_found 正在作为字符串加载。当我在 mongohub 中运行它时:

{"date_found" : /.*2015-05-02.*/}

我得到了所有带有“2015-05-02”的集合。太棒了!

但是,当我运行时:

for item in collection.find({"date_found": "/.*2015-05-02.*/"}):
    print item

我什么也得不到。

还有,这个:

for item in collection.find():
    print item

给了我所有的集合,所以似乎一切都在我可以查询数据库的范围内工作。

有人能告诉我我犯了什么愚蠢的错误(或者我错过了什么)吗?

【问题讨论】:

    标签: python mongodb python-2.7 pymongo


    【解决方案1】:

    在 pymongo 中,要包含 regular expression,您可以尝试这样的操作:

    import re
    regx = re.compile(".*2015-05-02.*")
    for item in collection.find({"date_found": regx})
        print item
    

    或使用$regex 运算符:

    import re
    regx = re.compile(".*2015-05-02.*")
    for item in collection.find({"date_found": {"$regex": regx} })
        print item
    

    【讨论】:

    • 这两个都在 regx 行抛出“sre_constants.error: nothing to repeat”...
    • 看起来这些正则表达式字符串中缺少前导 .
    • 我已经更新了答案,包括领先的.。感谢@JohnnyHK 的提醒。
    • 就像一个魅力。你介意解释一下区别吗?我假设它与 pymongo 有关,但我不太确定......只是想理解。再次感谢!
    • 基本上前面的. 匹配除换行符以外的任何字符,最好用Python 2.7 Regular Expressions Cheat Sheet 解释。
    猜你喜欢
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 2017-09-08
    • 1970-01-01
    相关资源
    最近更新 更多