使用正则表达式 returns 的 PyMongo 查询尽管 if: elif: else

PyMongo query with regex returns nothing despite if: elif: else

出于某种奇怪的原因,我有一个 Mongo 查询 returns 几乎什么都没有(没有数据的空白行),尽管使用了一个看起来无法逃脱的条件。要重现(假设你安装了 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,即使那个 something 是 None。但是它的 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"}}}}}}):
    # ...

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

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

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.