Nelly Brili Nelly Brili - 1 year ago 138
Python Question

Update MongoDB collection using Python

I have a MongoDB and documents are like this:

enter image description here

I have a text file that include some words and their sentiment scores.
If the word is in the testcollection as "surfaceEnd", I want to update some fields. Otherwise, I want to insert a new row.

for w in words:
print w
if db.testcollection10.find({ 'surfaceEnd': w }) == True:
posnum = float(get_positive(cols))
negnum = float(get_negative(cols))
db.testcollection.update({ 'surfaceEnd': w}, {"$set": { 'posEnd': posnum,'negEnd': negnum,'findEnd' : 1 }})
i = i + 1
cursor = db.collectionNelly.find({ 'surfaceStart': w })

for document in cursor:
relation = document['rel']
word = document['surfaceEnd'].encode('utf-8')
posnum = float(get_positive(cols))
negnum = float(get_negative(cols))
if 'Synonym' in document['rel']:
db.testcollection1.insert ({ 'surfaceStart': w,'posStart': posnum, 'negStart': negnum, 'surfaceEnd': word,'posEnd': posnum,'negEnd': negnum, 'rel' : document['rel'], 'findEnd' : 0 })

Unfortunately, the testcollection could not be created. What is the problem in this code?

Answer Source

PyMongo's find operation returns a cursor and not a boolean value. You want to determine how many records were returned and act accordingly.

for w in words:
        print w
        items = db.testcollection10.find({ 'surfaceEnd': w })
        if items.count() > 0:
            # The surfaceEnd entry was found update it.
            # The surfaceEnd entry was not found, insert a new one.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download