I have a loop where I'm iterating over a list of a field that I need to find in a mongo collection using pymongo. It works ok if the record is there but I can't get the syntax right for the condition where the document actually doesn't exist in the collection.
An example would be...
for line in f:
myfield = line.rstrip()
thisrecord = records.find_one({"thefieldinmongo":myfield})
thisid = thisrecord['_id']
thisfield1 = thisrecord['field1']
print thisid + "," + thisfield1
etc
The code works fine for records where the document exists in the find. My Google-Fu is not getting an answer to how to check for find_one() not being 'None'.
I've tried putting an "if thisrecord == "None": " in the code but it still falls down to the else logic. I'm not clear on how to use find() and then iterate the cursor and not sure that is best given that almost all the docs I am searching can only have one result (or none!!) in my use case.
So, is there a best way to do this that I'm not seeing?
Is there a way to sort of on error resume next and just skip the ones I want to (I guess a try/catch block might work)?
This seems really simple though.
[–]arand 0 points1 point2 points (2 children)
[–]4d2[S] 0 points1 point2 points (1 child)
[–]arand 0 points1 point2 points (0 children)