【问题标题】:insert and update list of dictionary in pymongo在 pymongo 中插入和更新字典列表
【发布时间】:2015-06-19 09:27:15
【问题描述】:

我在数据库中有日期是唯一键的记录。对于每条记录,我都有日期和结果字段。

result 字段是字典列表,字典有两个值。 如果新记录出现在同一日期,它应该以不同的方式将字典附加到现有字典中。

这是代码,print "updated records ", record 为我提供了更新不同的字典列表。但是更新命令不会将其反映在数据库上。数据库内容与以前相同。

def saveEntity(self, record):
    try:
        self.collection.insert(record)
        print "mongo done"
    except Exception:
        data = self.collection.find({'date': 2})
        for key in data:
            print "db record : ",key
            record['result'].extend([k for k in key['result'] if k not in record['result']])
        print "updated records ", record    --- X
        for key in data:
            self.collection.update(
                {'date' : 2},
               {'result':record['result']},
               True
        )

记录的原始内容['result']:

[{"a": 1, "city" : "p"}, {"b": 2, "city" : "a"}]

同一天有新内容

[{"a": 1, "city" : "p"}, {"c": 3, "city" : "m"}]

根据代码行更新内容X

[{'a': 1, 'city': 'p'}, {'city': 'm', 'c': 3}, {u'city': u'a', u'b': 2}]

请不要在这里u,不知道原因。

数据库内容在最后

[{"a": 1, "city" : "p"}, {"b": 2, "city" : "a"}]

这里的问题是,它应该用新的附加字典列表更新数据库,但它没有

【问题讨论】:

  • 那么这里的问题是什么?
  • @user3100115:更新了描述

标签: python mongodb dictionary


【解决方案1】:

尝试在您的更新中包含 $set 更新运算符修饰符:

self.collection.update({'date' : 2}, { '$set': {'result': record['result']} }, True)

【讨论】:

    猜你喜欢
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 2016-07-03
    • 1970-01-01
    • 2017-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多