2013-02-26 87 views
1

使用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

回答

0

您的查詢不工作,因爲你要查詢的鍵中使用「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

25

012ym的pymongo版本是Python None。所以query應該是這樣的:

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