使用Python更新MongoDB集合

2024-09-23 06:30:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个MongoDB,文档如下:

enter image description here

我有一个文本文件,其中包括一些词和他们的情绪得分。 如果testcollection中的单词是“surfaceed”,我想更新一些字段。否则,我要插入新行。你知道吗

 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  })

很遗憾,无法创建testcollection。这个代码有什么问题?你知道吗


Tags: infordbgetiffindfloatdocument
1条回答
网友
1楼 · 发布于 2024-09-23 06:30:43

PyMongo的find操作返回一个游标,而不是布尔值。您需要确定返回了多少条记录并采取相应的措施。你知道吗

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.

相关问题 更多 >