在MongoDB中查询空值

问题描述:

使用pymongo我试图检索具有与null不同的SmallUrl集合中的文档。我正在尝试获取密钥names和密钥SmallUrl在MongoDB中查询空值

如果我只查找Name,查询运行良好。但是,由于我想从结果中筛选出null值为SmallUrl的文档,因此当我在查询中包含此值时,查询将不返回任何内容。

这是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')} 

这是查询功能:我是新来的MongoDB我尝试不同的查询已经

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() 

。我已经使用$and,$not,{'$ne': 'null'}}。我也在mongoShell中运行了查询,但结果相同。这是我在shell中查询的一个例子:

db.myCollection.find({'Name': {'$regex': 'luis', '$options': 'i'}, 'SmallUrl': {'$ne': null}}) 

我想知道我在做什么错误。

+0

没有使用Python中的地方空 – hamed 2016-10-18 11:48:51

您的查询不工作,因为你要查询的键中使用“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" } 

和我的测试查询:

> db.t.find({'Images.SmallUrl': {$ne: null}}) 
{ "_id" : ObjectId("512cdbb365fa12a0db9d8c35"), "Images" : { "LargeUrl" : "http://aaa.com", "SmallUrl" : "http://bb.com" }, "Name" : "yy" } 

希望能帮到^ _^

+0

的非常感谢你。 – lv10 2013-02-26 20:58:42

012ym的pymongo版本是Python None。所以query应该是这样的:

query = { 
    'Name': {'$regex': search_title, '$options': 'i'}, 
    'Images.SmallUrl': {'$ne': None}}