在python dict中添加新的键值对
当我试图在python字典中添加一个新的键值对,同时保留以前的键值对时,我遇到了一个问题。我正在使用在python dict中添加新的键值对,python,mongodb,Python,Mongodb,当我试图在python字典中添加一个新的键值对,同时保留以前的键值对时,我遇到了一个问题。我正在使用MongoDB作为数据库 我的样本回答是 "field1" : "a", "field2" : "b", "field3" : "c", "history" : { "2019-09-03 00:00:00" : "state1" } "field1" : "a", "field2" : "b", "field3" : "c", "history" : { "2019-09-01
MongoDB
作为数据库
我的样本回答是
"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : {
"2019-09-03 00:00:00" : "state1"
}
"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : {
"2019-09-01 00:00:00" : "state1"
"2019-09-02 00:00:00" : "state1"
"2019-09-03 00:00:00" : "state1"
}
预期的反应是
"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : {
"2019-09-03 00:00:00" : "state1"
}
"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : {
"2019-09-01 00:00:00" : "state1"
"2019-09-02 00:00:00" : "state1"
"2019-09-03 00:00:00" : "state1"
}
我想在历史记录中添加键值对,键是date,值是state,但问题是我的代码删除了以前的键值对,然后添加一个新的键值对
我正在使用mongo-client
在MongoDB数据中保存一条记录
这是我的密码
out = dict()
history = dict()
out['field1'] = 'a'
out['filed2'] = 'b'
out['field3'] = 'c'
history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0))] = 'state1'
out_handle.update_one(
{'field1': a, 'field2': 'b', 'field3': 'c'},
{'$set': out}},
upsert=True
)
这可以是一种解决方案:
创建要插入父词典的子词典:
history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, day=1))] = 'state1'
history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, day=2))] = 'state1'
history[str(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0, day=3))] = 'state1'
将子词典插入父“外”词典中
out['history']=history
影响
{'field1': 'a',
'filed2': 'b',
'field3': 'c',
'history': {'2019-09-03 00:00:00': 'state1',
'2019-09-02 00:00:00': 'state1',
'2019-09-01 00:00:00': 'state1'}}
看起来您希望通过三个字段
{'field1':a,'field2':'b','field3':'c'}
进行查询,然后只添加历史记录。使用$push
操作符执行此操作。注意,update\u one
的第二个参数可以有$push
和$set
和$unset
操作符
coll.update_one({'field1': a, 'field2': 'b', 'field3': 'c'}, {
"$push": {"history":{"D2":"S3"}},
"$set": {"otherField1": "hello", "otherField2": "goodbye"}
}, upsert=True)
但是
我强烈建议您不要使用日期作为键,而是作为值,以及作为实时日期时间值,而不是字符串。当日期查询是一个值而不是一个键时,处理它们就容易多了
rec = {
"date": datetime.datetime.now(),
"state": "state1" # or whatever
}
coll.update_one({'field1': a, 'field2': 'b', 'field3': 'c'}, {"$push": {"history":rec}} )
这会产生如下结果:
{
"field1" : "a",
"field2" : "b",
"field3" : "c",
"history" : [
{
"date" : ISODate("2019-09-03T07:54:38.144Z"),
"state" : "state1"
},
{
"date" : ISODate("2019-09-03T07:54:38.144Z"),
"state" : "state2"
}
]
}
您好,我还有一个DictField,而不是
history
,所以我使用了“$set”:out
,但是如果我使用set
和push
一起使用,我会得到错误类型错误:update_one()为参数'upsert'
获得多个值。