简体   繁体   English

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

[英]insert and update list of dictionary in pymongo

I have records in database where date is unique key. 我在数据库中有记录,其中日期是唯一键。 For each record I have date and result fields. 对于每个记录,我都有日期和结果字段。

result field is list of dictionaries, dictionary having two value. 结果字段是字典列表,具有两个值的字典。 if new record comes for same date, it should appends the dictionaries to existing dictionary in distinct manner. 如果新记录到达同一日期,则应以不同的方式将字典追加到现有字典中。

This is the code, where print "updated records ", record gives me updates distinct list of dictionary. 这是代码,其中print "updated records ", record为我提供了字典的更新列表。 But updates command does not reflect it on database. 但是updates命令不会在数据库上反映出来。 Database content remains same as before. 数据库内容与以前相同。

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
        )

Original content for record['result']: 记录的原始内容['结果']:

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

New content comes for same date 新的内容是在同一日期

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

updated content as per code line X 按照代码行X更新内容

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

Please not u here, dont know the reason. 请不要u在这里,不知道原因。

Database content at the end 最后的数据库内容

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

Problem here is, it should update the database with new appended list of dictionary, but it does not 这里的问题是,它应该使用新的字典附加列表来更新数据库,但是不会

尝试在更新中包括$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