广西建设工程管理网站,深圳住建设局官方网站,包头怎样做网站,wordpress集团网站本篇文章介绍mongodb的删和改#xff0c;下面是前两篇文章的链接#xff1a; 【fastapimongodb】使用motor操作mongodb 【fastapimongodb】使用motor操作mongodb#xff08;二#xff09;
delete
delete 的用法基本和查找一致#xff0c;包括delete_one#xff08;删除…本篇文章介绍mongodb的删和改下面是前两篇文章的链接 【fastapimongodb】使用motor操作mongodb 【fastapimongodb】使用motor操作mongodb二
delete
delete 的用法基本和查找一致包括delete_one删除一个delete_many匹配到的全部删除我们以delete_one为例
async def delete_user_by_name(name: str):delete_result await collection_users.delete_one({name:name})print(delete_result)loop.run_until_complete(delete_user_by_name(bluebonnet27))打印出来的result如下
DeleteResult({n: 1, ok: 1.0}, acknowledgedTrue其实这个result看源代码就知道它的结构了
class DeleteResult(_WriteResult):The return type for :meth:~pymongo.collection.Collection.delete_oneand :meth:~pymongo.collection.Collection.delete_many__slots__ (__raw_result,)def __init__(self, raw_result: Mapping[str, Any], acknowledged: bool) - None:self.__raw_result raw_resultsuper().__init__(acknowledged)def __repr__(self) - str:return f{self.__class__.__name__}({self.__raw_result!r}, acknowledged{self.acknowledged})propertydef raw_result(self) - Mapping[str, Any]:The raw result document returned by the server.return self.__raw_resultpropertydef 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为例子
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
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)
loop.run_until_complete(update_name_of_user_by_age(30, name))我们将刚才的数据重新修改了下现在它是这样的