2 回答

TA貢獻1790條經驗 獲得超9個贊
看起來您希望通過三個字段進行查詢{'field1': a, 'field2': 'b', 'field3': 'c'},然后只需添加一條歷史記錄。與$push操作員一起這樣做。注意第二個參數update_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"
}
]
}

TA貢獻1802條經驗 獲得超5個贊
這可以是解決方案:
創建子字典以插入父字典:
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”字典中插入子字典
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'}}
添加回答
舉報