这篇文章本来要介绍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(二)
E-->