Querying null value in MongoDB

2019-02-11 02:01发布

Using pymongo I am trying to retrieve the documents in a collection that have a SmallUrl different from null. I'm trying to get the names key and the SmallUrl key.

If I look for the Name only, the query runs fine. However, since I want to filter out from the results the documents that have a null value for SmallUrl, when I include the this in the query, the query returns nothing.

This is the MongoDB structure:

{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')}

This is the function for the query:

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

I am new to MongoDB I tried different queries already. I have used $and, $not, {'$ne': 'null'}}. I also ran the queries in the mongoShell, but same result. This is an example of what I have queried in the shell:

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

I would like to know what I am doing wrong.

2条回答
成全新的幸福
2楼-- · 2019-02-11 02:30

your query does not work because you should use 'Images.SmallUrl' instead of 'SmallUrl' for the key of query. my test collection:

> 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" }

and my test query:

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

Hope to help ^_^

查看更多
Luminary・发光体
3楼-- · 2019-02-11 02:36

The pymongo version of null is the Python None. So query should look like:

query = {
    'Name': {'$regex': search_title, '$options': 'i'}, 
    'Images.SmallUrl': {'$ne': None}}
查看更多
登录 后发表回答