插入并更新pymongo中的字典列表

时间:2015-06-19 09:27:15

标签: python mongodb dictionary

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

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

这是代码,其中import argparse import datetime import imutils import time import cv2 import numpy as np ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to video") ap.add_argument("-a", "--min-area", type=int, default = 200, help="min area") args=vars(ap.parse_args()) if args.get("video", None) is None: camera = cv2.VideoCapture(0) camera.set(cv2.cv.CV_CAP_PROP_FPS,2) camera.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH,640) camera.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT,480) time.sleep(2.5) else: camera = cv2.VideoCapture(args["video"]) while True: (grabbed, frame) = camera.read() if not grabbed: break frame = imutils.resize(frame, width=500) cv2.imshow("testing",frame) key = cv2.waitKey(1) & 0xFF if key == ord("q"): break camera.release() cv2.destroyAllWindows() 为我提供了更新的字典列表。但是更新命令不会在数据库上反映它。数据库内容与以前保持一致。

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
        )

新内容来自同一日期

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

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

1 个答案:

答案 0 :(得分:1)

尝试在更新中加入 $set 更新操作符修饰符:

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