nlper
nlper

Reputation: 2407

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. But updates command does not reflect it on database. 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

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

Please not u here, dont know the reason.

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

Upvotes: 0

Views: 5038

Answers (1)

chridam
chridam

Reputation: 103445

Try including the $set update operator modifier in your update:

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

Upvotes: 1

Related Questions