user94628
user94628

Reputation: 3721

Mongo query doesnt recognise empty records

I'm going through my collection and returning coordinate information, however when it hits an empty record it throws this error:

a=get_coords(doc['coordinates']['coordinates'])
print a

This is the function get_coords:

def get_coords(doc):
    if doc == None:
        pass
    else:
        longs, lat = doc

        return lat, longs

The error:

TypeError: 'NoneType' object has no attribute '__getitem__'

This then stops my query and no further records are returned.

How can I prevent this from happening, what I mean is I still want it to carry on searching for other records rather than stopping with this error message.

Thanks

Thanks for both answers they both helped. I was able to get it done by:

if doc['coordinates']==None:
    pass
else: 
    b=get_coords(doc['coordinates']['coordinates'])
    print b

I do this after first checking that there is indeed a doc in the collection. It now seems to print all existing coordinates in the collection.

Thanks

Upvotes: 1

Views: 502

Answers (3)

aga
aga

Reputation: 29416

You also could use exception handling to rewrite get_coords() function like this:

def get_coords(doc):
    try:
        longs, lat = doc
        return lat, longs
    catch TypeError:
        return None, None

Upvotes: 1

RocketDonkey
RocketDonkey

Reputation: 37249

Will doc always have a coordinates attribute? If so, will that dictionary always have another coordinates attribute? Assuming doc will always be dictionary (even just a blank one), you can try this:

In [90]: def get_coords(doc):
   ....:     if doc.get('coordinates', None):
   ....:         if doc['coordinates'].get('coordinates', None):
   ....:             return doc['coordinates']['coordinates']
   ....:     return None, None
   ....:

In [91]: doc
Out[91]:
{'coordinates': {u'coordinates': [-81.453134399999996, 28.5287337],
                 u'type': u'Point'}}

In [92]: get_coords(doc)
Out[92]: [-81.453134399999996, 28.5287337]

In [93]: new_doc = {'coordinates': {u'type': u'Point'}}

In [94]: get_coords(new_doc)
Out[94]: (None, None)

In [95]: empty_doc = {}

In [96]: get_coords(empty_doc)
Out[96]: (None, None)

Notice that the return value is two items, so when you call the function, you need to be prepared to accept two return items. If there is no coordinates in doc, it will return None, None.

In [101]: lat, long = get_coords(doc)

In [102]: lat
Out[102]: -81.453134399999996

In [103]: long
Out[103]: 28.5287337

Upvotes: 1

rofls
rofls

Reputation: 5115

I'm not sure why you're printing b, since that's not defined in the above code. Maybe you mean a?

Either way, you should be able to do:

if doc==None:
   pass
else:
   a=get_coords(doc['coordinates']['coordinates'])
   print b

or whatever you want to do with doc. If some doc items don't have coordinates you'll need to do something similar for that.

Upvotes: 2

Related Questions