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.
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}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With