pymongo更新无效

0 投票
1 回答
3341 浏览
提问于 2025-04-18 10:43

首先,我找到一个文档,并通过findandmodify()方法把它的状态值更新为1。然后我用这个文档做一些事情。之后,我想用它的对象ID把文档的状态更新为2,我用的方法是update()。
但是,经过这样的操作后,状态值并没有变成2。以下是我代码的简化版本:

try:
    print 'update...'
    db.Tuser.update({'_id':obj_id},  # obj_id is a bson object, it's the object id of the document
                    {'$set':{'state': 2}})
    print 'update done'
except Exception as e:
    print 'update failed: %s' % str(e)

输出结果是:
更新中...
更新完成

顺便说一下,这种情况发生在我在8台电脑上运行时,只有2台能够成功更新。而当我单独运行时,一切正常。

1 个回答

1

试试一些基本的调试步骤 - 这个有没有返回什么结果呢?

db.Tuser.find({'_id':obj_id},
                {'$set':{'state': 2}})

obj_id是字符串还是bson对象呢?

type(obj_id)

如果是字符串的话,你需要把它转换成bson对象。

import bson
obj_id = bson.ObjectId(obj_id)

撰写回答