当前位置: 首页> 房产> 政策 > 【fastapi+mongodb】使用motor操作mongodb(二)

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

时间:2025/7/9 15:28:50来源:https://blog.csdn.net/qq_37387199/article/details/139546628 浏览次数:0次

这篇文章本来要介绍valgrind的,但是valgrind只能安装在 Linux 上,不得已,就继续上一篇文章写motor的用法。

如果你还没看过上一篇文章,地址在这:【fastapi+mongodb】使用motor操作mongodb

select

删除和修改都是基于查询的语法的。
使用 find_one() 得到匹配查询的第一个文档:

async def find_user_by_name():document_user = await collection_users.find_one({'name':'bluebonnet27'})print(document_user)

find_one支持匹配词进行辅助,和mongodb的方法一样。比如你只想返回名字(这要求很奇怪),可以这么写:

async def find_user_by_name_return_name():document_user = await collection_users.find_one({'name':'bluebonnet27'}, {'name': 1})print(document_user)

输出如下:

{'_id': ObjectId('6653321bbca655e427d1196f'), 'name': 'bluebonnet27'}

当然,同样的办法,如果_id也不想看到,也可以把它排除掉:

async def find_user_by_name_return_name():document_user = await collection_users.find_one({'name':'bluebonnet27'}, {'name': 1, '_id': 0})print(document_user)

find_one()同样支持条件匹配。比如,我们要查询年龄小于某个数字的user(lt是 less than):

async def find_user_by_lower_age(age: int):document_user = await collection_users.find_one({'age':{'$lt': age}})print(document_user)

使用 find() 可以查询一组文档。 find() 没有I / O,也不需要 await 表达式。它只是创建一个 AsyncIOMotorCursor 实例。调用to_list时,才需要进行await操作。注意,需要在to_list中指定length的大小,否则无法处理缓冲区溢出的问题:

async def find_users_by_name(name: str):users_cursor = collection_users.find({'name':name})for document_user in await users_cursor.to_list(length=100):print(document_user)

输出如下:

{'_id': ObjectId('6653321bbca655e427d1196f'), 'name': 'bluebonnet27', 'age': 24}
{'_id': ObjectId('6653323a3a2f7378d4fee103'), 'name': 'bluebonnet27', 'age': 24}
{'_id': ObjectId('6653325dfba58f88883ecd31'), 'name': 'bluebonnet27', 'age': 24}
{'_id': ObjectId('666404d0bd455a936bbf9dee'), 'name': 'bluebonnet27', 'age': 24}
{'_id': ObjectId('66650ee7ba035059d15c5b1d'), 'name': 'bluebonnet27', 'age': 24}
{'_id': ObjectId('666510181342c1d39f1b17e8'), 'name': 'bluebonnet27', 'age': 24}
{'_id': ObjectId('6665116aec1e9c66564df13d'), 'name': 'bluebonnet27', 'age': 24}

另一种写法是直接用async forcursor进行遍历:

async def find_users_by_name2(name: str):async for document_user in collection_users.find({'name':name}):print(document_user)

效果是一样的。

如果只是希望查询满足某个条件的文档的数量,可以使用count_documents(),这是更简单的函数:

async def get_users_num_by_name(name: str):return await collection_users.count_documents({'name':name})

main

    count: int = loop.run_until_complete(get_users_num_by_name('bluebonnet27'))print(count)
关键字:【fastapi+mongodb】使用motor操作mongodb(二)

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: