我有一个 MongoDB 集合,其中包含如下从 starting_dict 创建的文档:
from pymongo import MongoClient
test = MongoClient(mongo_connection_string).database_name.test
starting_dict = {
'Colors': [ 'green', 'blue' ],
'Dimensions': {
'Lenght': 10,
'Height': 20
}
}
test.insert_one( { 'Name': 'Test1', 'Description': starting_dict } )
给出:
{'_id': ObjectId('6436a68bc3ada18c371339e9'),
'Name': 'Test1',
'Description': {'Colors': ['green', 'blue'],
'Dimensions': {'Lenght': 10, 'Height': 20}}}
现在,我想用另一个字典更新文档:
updated_dict = {
'Colors': [ 'yellow' ],
'Dimensions': {
'Depth': 5
}
}
我的需求是:
保留其他字段不变。
但是,使用这个命令:
test.update_one( { 'Name': 'Test1'}, [ { '$addFields': { 'Description': updated_dict } } ] , upsert=False)
我得到:
{'_id': ObjectId('6436a68bc3ada18c371339e9'),
'Name': 'Test1',
'Description': {'Colors': ['yellow'],
'Dimensions': {'Lenght': 10, 'Height': 20, 'Depth': 5}}}
所以,“尺寸”是正确的,但是“颜色”数组丢失了
starting_dict
中的先前元素。
是否可以在更新文档时保留数组元素?
你可以将颜色推入颜色数组.. (同样尺寸也)
检查下面的链接
https://www.mongodb.com/docs/manual/reference/operator/update/push/
否则您需要将旧数据添加到更新后的数组中,然后再添加其余代码...