6

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.

1
  • 1
    use None in python in place of null Commented Oct 18, 2016 at 11:48

2 Answers 2

52

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}}
Sign up to request clarification or add additional context in comments.

Comments

0

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 ^_^

1 Comment

There is no such thing as null in Python

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.