当前位置:首页 > 日记本 > 正文内容

python 多线程 mongodb数据库:motor代码示例

zhangchap2年前 (2022-04-10)日记本431
# -*- coding: utf-8 -*-
from motor import motor_asyncio
import asyncio
import platform

if "Windows" in platform.platform():
    policy = asyncio.WindowsSelectorEventLoopPolicy()
    asyncio.set_event_loop_policy(policy)


async def init():
        client = motor_asyncio.AsyncIOMotorClient()
    # client = motor_asyncio.AsyncIOMotorClient('mongodb://127.0.0.1:27017')

    # 创建或连接数据库
    db = client['kanchai']

    # 创建或连接集合(表)
    colllection = db['article']
    return colllection


async def find_one(collection, title):
    result = await collection.find_one({"title": title}, {"_id": 0})
    print(result)

async def find_all(collection, skip, limit):
    # cousor = collection.find({}, skip=skip, limit=limit)
    # for item in await cousor.to_list(length=limit):
    #     print(item)

    async for item in collection.find({}, {"_id": 0}, skip=skip, limit=limit):
        print(item)

async def count_all(collection):
    counts = await collection.count_documents({})
    print(counts)

async def update_document(collection, title):
    ret = await collection.update_one({"title": title}, {"$set": {"isindex": 1}})
    print(ret.modified_count)

async def delete_document(collection, title):
    # ret = await collection.delete_one({"title": title})
    ret = await collection.delete_many({"title": title})
    print(f"成功删除:{ret.deleted_count}个文档")
    print(ret.acknowledged)
    print(ret.raw_result)


async def main():
    collection = await init()
    title = "全链路数字化转型下,零售企业如何做到消费者“心智占领”"
    await find_one(collection, title)
    # await find_all(collection, 9, 10)
    # await count_all(collection)
    # await update_document(collection, title)
    await delete_document(collection, title)



asyncio.run(main())


分享给朋友:

相关文章

python 函数 开启多线程示例

from threading import Thread def readfile(queue:Queue):    &nbs...

python xpath语法总结

python xpath语法总结:常用的://1.从任意节点开始/2.从根节点开始//div/p3.div下的p标签//div[@class="hrzz_bottom"]/ul/l...

python url.parse模块编码解码

from urllib.parse import quote,unquote,urlencode # 对汉字进行编码使用 quote ...

python读取txt文件放到Queue队列

from queue import Queue with open('kw.txt',encoding='utf-8')&nb...

减重五原则

1.主粮减半,少吃米面粥粉等;2.完全戒糖,包括可乐、奶茶等3.轻断食,每周一次,一日餐4.不限制任何动物脂肪和肉类,少吃植物油;5.保证随时喝到水,脂肪的消耗需要大量的水。...

如何为精简的 CSS 文件删除未使用的 CSS

如何为精简的 CSS 文件删除未使用的 CSS

精简的网站比臃肿的网站运行得更快,这已经不是什么秘密了。不要让不必要的 CSS 拖累您的 Web 项目;使用下面描述的工具和技术来帮助您删除未使用的 CSS 并提高您网站的整体性能。什么是未使用的 C...

发表评论

访客

◎欢迎参与讨论,请在这里发表您的看法和观点。