使用pymongo我试图检索一个与之SmallUrl不同的集合中的文档null.我正在努力获得names钥匙和SmallUrl钥匙.
如果我Name只查找,查询运行正常.但是,由于我想从结果中过滤掉具有null值的文档SmallUrl,当我在查询中包含this时,查询不返回任何内容.
这是MongoDB结构:
{u'Images': {u'LargeUrl': u'http://somelink.com/images/7960/53.jpg',
u'SmallUrl': u'http://somelink.com/images/7960/41.jpg'}
u'Name': u'Some Name',
u'_id': ObjectId('512b90f157dd5920ee87049e')}
{u'Images': {u'LargeUrl': u'http://somelink.com/images/8001/53.jpg',
u'SmallUrl': null}
u'Name': u'Some Name Variation',
u'_id': ObjectId('512b90f157dd5820ee87781e')}
Run Code Online (Sandbox Code Playgroud)
这是查询的功能:
def search_title(search_title):
$ne
''' Returns a tuple with cursor (results) and the size of the cursor'''
query = {'Name': {'$regex': search_title, '$options': 'i'}, 'SmallUrl': {'$exists': True}}
projection = {'Name': 1, 'Images': 1}
try:
results = movies.find(query, projection)
except:
print "Unexpected error: ", sys.exc_info()[0]
$ne
return results, results.count()
Run Code Online (Sandbox Code Playgroud)
我是MongoDB的新手我已经尝试了不同的查询.我已经使用$and,$not,{'$ne': 'null'}}.我还在mongoShell中运行了查询,但结果相同.这是我在shell中查询的一个例子:
db.myCollection.find({'Name': {'$regex': 'luis', '$options': 'i'}, 'SmallUrl': {'$ne': null}})
Run Code Online (Sandbox Code Playgroud)
我想知道我做错了什么.
Joh*_*yHK 37
pymongo版本null是Python None.所以query应该看起来像:
query = {
'Name': {'$regex': search_title, '$options': 'i'},
'Images.SmallUrl': {'$ne': None}}
Run Code Online (Sandbox Code Playgroud)
您的查询不起作用,因为您应该使用“Images.SmallUrl”而不是“SmallUrl”作为查询键。我的测试集合:
> db.t.find()
{ "_id" : ObjectId("512cdbb365fa12a0db9d8c35"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : "http://bb.com" }, "Name" : "yy" }
{ "_id" : ObjectId("512cdc1765fa12a0db9d8c36"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : null }, "Name" : "yy" }
Run Code Online (Sandbox Code Playgroud)
和我的测试查询:
> db.t.find({'Images.SmallUrl': {$ne: null}})
{ "_id" : ObjectId("512cdbb365fa12a0db9d8c35"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : "http://bb.com" }, "Name" : "yy" }
Run Code Online (Sandbox Code Playgroud)
希望能帮到你^_^
| 归档时间: |
|
| 查看次数: |
12394 次 |
| 最近记录: |