简体   繁体   中英

Update MongoDB collection using Python

I have a MongoDB and documents are like this:

在此处输入图片说明

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
            else:
                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?

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.
        else:
            # The surfaceEnd entry was not found, insert a new one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM