【发布时间】: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