繁体   English   中英

在pymongo中插入和更新字典列表

[英]insert and update list of dictionary in pymongo

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

结果字段是字典列表,具有两个值的字典。 如果新记录到达同一日期,则应以不同的方式将字典追加到现有字典中。

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

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
        )

记录的原始内容['结果']:

[{"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"}]

这里的问题是,它应该使用新的字典附加列表来更新数据库,但是不会

尝试在更新中包括$set update运算符修饰符:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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