【问题标题】:MongoDB pymongo update() simply creates a new record rather than updatingMongoDB pymongo update() 只是创建一个新记录而不是更新
【发布时间】:2012-10-03 05:39:09
【问题描述】:

创建一个新文档

>>>Categories.insert({'test':'test'})
ObjectId('506b563df49a007f73000001')

是的,创建成功。

>>> Categories.find_one({'test':'test'})
{u'test': u'test', u'_id': ObjectId('506b4149f49a007cd0000000')}

给它一个新属性“newAttr”,值为“hello”

>>> Categories.update({'_id':Categories.find_one({'test':'test'})['_id']},{'newAttr':'hello'})

查找相同的文档

>>> Categories.find_one({'test':'test'})
{u'test': u'test', u'_id': ObjectId('506b563df49a007f73000001')}

还没更新??

搜索包含新属性的内容:

>>> Categories.find_one({'newAttr':'hello'})
{u'newAttr': u'hello', u'_id': ObjectId('506b4149f49a007cd0000000')}

它创建了一个单独的文档而不是更新之前的文档??

知道如何纠正这个问题吗?

【问题讨论】:

  • 如果你想添加一个新字段,你需要使用 {$set:{'field':'name'}) - 你拥有它的方式是你告诉它将文档更新为一个全新的价值...

标签: mongodb pymongo


【解决方案1】:

我在设置新字段时得到的和你不一样,但我使用的是这种语法:

cat.update({'_id':cat.find_one({'test':'test'})['_id']},{'$set':{'newattr':'hello'}})

$set 解释见here

>>> cat.find_one({'test':'test'})
{u'newattr': u'hello', u'test': u'test', u'_id': ObjectId('506b5d07594bc07d90000000')}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2012-07-25
    • 2021-03-30
    相关资源
    最近更新 更多