背景:
某次开发中需要修改字段名称,由于时间紧,而自己对mongodb不熟,按照基本逻辑写完了代码并实现了功能,事后学习官方文档有更好的方法。
数据准备
ret = test_coll.insert_many([
{
"_id": 1,
"alias": ["The American Cincinnatus", "The American Fabius"],
"mobile": "555-555-5555",
"nmae": {"first": "george", "last": "washington"}
},
{
"_id": 2,
"alias": ["My dearest friend"],
"mobile": "222-222-2222",
"nmae": {"first": "abigail", "last": "adams"}
},
{
"_id": 3,
"alias": ["Amazing grace"],
"mobile": "111-111-1111",
"nmae": {"first": "grace", "last": "hopper"}
},
],
)
# 文档中的nmae写错了, 需要改为name
解决方法:
# 方法1:查询所有的文档 遍历判断然后依次修改
def update_to_rename_one_by_one():
documents_cursor = test_coll.find({})
for document in documents_cursor:
if 'nmae' in document.keys():
_id = document['_id']
name = document['nmae']
document.pop('nmae')
document['name'] = name
ret = test_coll.update_one({'_id': _id}, {"$set": document})
if ret.modified_count:
print('rename success')
# 方法二:
def update_to_rename_all():
ret = test_coll.update_many({}, {'$rename': {"nmae": "name"}})
return ret.modified_count
总结:
- 第一种方法 查询出来 再遍历,然后遍历过程中针对字典进行修改操作,然后修改数据库中的文档 ,第二种方法,在查询数据库中就针对名称进行了修改,少了内存开销与运行时间;
- mongodb的官方文档写的非常清晰,可以修改匹配中的第一个,也可以修改所有,还可以修改嵌套字典中的字段名称,详细请看https://docs.mongodb.com/manual/reference/operator/update/rename/