【问题标题】:PyMongo query with regex returns nothing despite if: elif: else使用正则表达式的 PyMongo 查询不返回任何内容,尽管 if: elif: else
【发布时间】:2015-12-08 16:26:09
【问题描述】:

出于某种奇怪的原因,我有一个 Mongo 查询,尽管使用了似乎无法逃脱的条件,但它实际上没有返回任何内容(没有数据的空白行)。重现(假设您安装了 PyMongo):

import pymongo
import re

manyNodesDeep = {
    "one": {
        "two": {
            "three": {
                "four": {
                    "five": "five"
                }
            }
        }
    }
}
fooBar = {
    "foo": "bar"
}

with pymongo.MongoClient() as conn:
    db = conn[u'local']

    collection = db.my_collection
    print "Collection: {}".format(collection)

    # clear collection
    collection.remove()

    collection.insert(manyNodesDeep)
    collection.insert(fooBar)

    # returns manyNodesDeep and fooBar objects:
    print "print node in collection.find():"
    for node in collection.find():
        print node

    # returns manyNodesDeep object:
    print "print node in collection.find() exact query"
    for node in collection.find({"one": {"two": {"three": {"four": {"five": "five"}}}}}):
        if node:
            print node
        else:
            print "no luck"

    # returns nothing at all:
    print "print node in collection.find() RegEx query"
    for node in collection.find({"one": {"two": {"three": {"four": {"five": re.compile("five", re.IGNORECASE)}}}}}):
        if node:
            print "regex: " + node
            print node
            print "TEST1"
        elif not node:
            print "regex: failed 1st if"
            print "TEST2"
        else:
            print "regex: failed both ifs"
            print "TEST3"

我本来希望最后一个语句打印 something,即使那是 None。但实际上根本没有打印出来……输出:

Collection: Collection(Database(MongoClient('localhost', 27017), u'local'), u'my_collection')
print node in collection.find():
{u'_id': ObjectId('55f39829e9e17246af559b5d'), u'one': {u'two': {u'three': {u'four': {u'five': u'five'}}}}}
{u'_id': ObjectId('55f39829e9e17246af559b5e'), u'foo': u'bar'}
print node in collection.find() exact query
{u'_id': ObjectId('55f39829e9e17246af559b5d'), u'one': {u'two': {u'three': {u'four': {u'five': u'five'}}}}}
print node in collection.find() RegEx query

Process finished with exit code 0

编辑:

也有人建议我这样尝试:

for node in collection.find({"one": {"two": {"three": {"four": {"five": {"$regex": "five"}}}}}}):
    # ...

但不幸的是,输出是相同的......

【问题讨论】:

    标签: regex mongodb python-2.7 pymongo


    【解决方案1】:

    在正则表达式匹配的情况下,您必须使用 点表示法

    collection.find({"one.two.three.four.five": re.compile(r"five")})
    

    忽略大小写:

    collection.find({"one.two.three.four.five": re.compile(r"FIVE", re.IGNORECASE)})
    

    解释here

    【讨论】:

    • 哦,哇,不错的发现。这太奇怪了(似乎在文档中找不到)。非常感谢!
    猜你喜欢
    • 2019-08-26
    • 1970-01-01
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-29
    • 2022-01-17
    相关资源
    最近更新 更多