【fastapi+mongodb】使用motor操作mongodb(三)

本篇文章介绍mongodb的删和改,下面是前两篇文章的链接:
【fastapi+mongodb】使用motor操作mongodb
【fastapi+mongodb】使用motor操作mongodb(二)

delete

delete 的用法基本和查找一致,包括delete_one(删除一个),delete_many(匹配到的全部删除),我们以delete_one为例:

python 复制代码
async def delete_user_by_name(name: str):
    delete_result = await collection_users.delete_one({'name':name})
    print(delete_result)
python 复制代码
loop.run_until_complete(delete_user_by_name('bluebonnet27'))

打印出来的result如下:

bash 复制代码
DeleteResult({'n': 1, 'ok': 1.0}, acknowledged=True

其实这个result看源代码就知道它的结构了:

python 复制代码
class DeleteResult(_WriteResult):
    """The return type for :meth:`~pymongo.collection.Collection.delete_one`
    and :meth:`~pymongo.collection.Collection.delete_many`
    """

    __slots__ = ("__raw_result",)

    def __init__(self, raw_result: Mapping[str, Any], acknowledged: bool) -> None:
        self.__raw_result = raw_result
        super().__init__(acknowledged)

    def __repr__(self) -> str:
        return f"{self.__class__.__name__}({self.__raw_result!r}, acknowledged={self.acknowledged})"

    @property
    def raw_result(self) -> Mapping[str, Any]:
        """The raw result document returned by the server."""
        return self.__raw_result

    @property
    def deleted_count(self) -> int:
        """The number of documents deleted."""
        self._raise_if_unacknowledged("deleted_count")
        return self.__raw_result.get("n", 0)

因此我们可以调用deleted_count方法返回被删除的数据个数,以及是否删除成功(delete方法本身是不会报异常的,没有满足要求的数据就什么都不执行)

update

更新主要是两类函数:replace和update,前者会用传入的对象整个覆盖掉document(就算你传入的是个空的document),后者可以选择修改哪些字段。

我们先以replace_one为例子:

python 复制代码
async def replace_user():
    document_user = await collection_users.find_one({'name':'bluebonnet28'})
    _id = document_user['_id']
    replace_result = await collection_users.replace_one({'_id': _id}, {'age': 30})
    print(replace_result.matched_count)
    print(replace_result.modified_count)

整个文档都会被替换,除了id,因此名字也没了,新的文档如下:

试试温和一点的update_one

python 复制代码
async def update_name_of_user_by_age(age: int, name: str):
    update_result = await collection_users.update_one({'age': age}, {'$set': {'name': name}})
    print(update_result.matched_count)
    print(update_result.modified_count)
python 复制代码
loop.run_until_complete(update_name_of_user_by_age(30, 'name'))

我们将刚才的数据重新修改了下,现在它是这样的:

相关推荐
oden11 小时前
AI服务商切换太麻烦?一个AI Gateway搞定监控、缓存和故障转移(成本降40%)
后端·openai·api
我一定会有钱11 小时前
斐波纳契数列、end关键字
python
李慕婉学姐12 小时前
【开题答辩过程】以《基于Android的出租车运行监测系统设计与实现》为例,不知道这个选题怎么做的,不知道这个选题怎么开题答辩的可以进来看看
java·后端·vue
小鸡吃米…12 小时前
Python 列表
开发语言·python
m0_7400437312 小时前
SpringBoot05-配置文件-热加载/日志框架slf4j/接口文档工具Swagger/Knife4j
java·spring boot·后端·log4j
星依网络13 小时前
yolov5实现游戏图像识别与后续辅助功能
python·开源·游戏程序·骨骼绑定
招风的黑耳13 小时前
我用SpringBoot撸了一个智慧水务监控平台
java·spring boot·后端
大佐不会说日语~13 小时前
Spring AI Alibaba 的 ChatClient 工具注册与 Function Calling 实践
人工智能·spring boot·python·spring·封装·spring ai
Miss_Chenzr13 小时前
Springboot优卖电商系统s7zmj(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
期待のcode13 小时前
Springboot核心构建插件
java·spring boot·后端