日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

【转】Python操作MongoDB数据库

發布時間:2024/10/12 python 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【转】Python操作MongoDB数据库 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • 前言
  • MongoDB GUI 工具
  • PyMongo(同步)
  • Motor(異步)
  • 后記

前言

最近這幾天準備介紹一下 Python 與三大數據庫的使用,這是第一篇,首先來介紹 MongoDB 吧,,走起!!

MongoDB GUI 工具

首先介紹一款 MongoDB 的 GUI 工具 Robo 3T,初學 MongoDB 用這個來查看數據真的很爽??梢约磿r看到數據的增刪改查,不用操作命令行來查看。?

PyMongo(同步)

可能大家都對 PyMongo 比較熟悉了,這里就簡單介紹它的增刪改查等操作。

連接

# 普通連接 client = MongoClient('localhost', 27017) client = MongoClient('mongodb://localhost:27017/') # # 密碼連接 client = MongoClient('mongodb://username:password@localhost:27017/dbname') db = client.zfdb # db = client['zfdb'] test = db.test View Code

# 增加一條記錄 person = {'name': 'zone','sex':'boy'} person_id = test.insert_one(person).inserted_id print(person_id) # 批量插入 persons = [{'name': 'zone', 'sex': 'boy'}, {'name': 'zone1', 'sex': 'boy1'}] result = test.insert_many(persons) print(result.inserted_ids) View Code

# 刪除單條記錄 result1 = test.delete_one({'name': 'zone'}) pprint.pprint(result1) # 批量刪除 result1 = test.delete_many({'name': 'zone'}) pprint.pprint(result1) View Code

# 更新單條記錄 res = test.update_one({'name': 'zone'}, {'$set': {'sex': 'girl girl'}}) print(res.matched_count) # 更新多條記錄 test.update_many({'name': 'zone'}, {'$set': {'sex': 'girl girl'}}) View Code

# 查找多條記錄 pprint.pprint(test.find())# 添加查找條件 pprint.pprint(test.find({"sex": "boy"}).sort("name")) View Code

聚合

如果你是我的老讀者,那么你肯定知道我之前的騷操作,就是用爬蟲爬去數據之后,用聚合統計結合可視化圖表進行數據展示。

aggs = [{"$match": {"$or" : [{"field1": {"$regex": "regex_str"}}, {"field2": {"$regex": "regex_str"}}]}}, # 正則匹配字段{"$project": {"field3":1, "field4":1}},# 篩選字段 {"$group": {"_id": {"field3": "$field3", "field4":"$field4"}, "count": {"$sum": 1}}}, # 聚合操作 ]result = test.aggregate(pipeline=aggs) View Code

例子:以分組的方式統計 sex 這個關鍵詞出現的次數,說白了就是統計有多少個男性,多少個女性。

test.aggregate([{'$group': {'_id': '$sex', 'weight': {'$sum': 1}}}]) View Code

聚合效果圖:(秋招季,用Python分析深圳程序員工資有多高?文章配圖)??

Motor(異步)

Motor 是一個異步實現的 MongoDB 存儲庫 Motor 與 Pymongo 的配置基本類似。連接對象就由 MongoClient 變為 AsyncIOMotorClient 了。下面進行詳細介紹一下。

連接

# 普通連接 client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://localhost:27017') # 副本集連接 client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://host1,host2/?replicaSet=my-replicaset-name') # 密碼連接 client = motor.motor_asyncio.AsyncIOMotorClient('mongodb://username:password@localhost:27017/dbname') # 獲取數據庫 db = client.zfdb # db = client['zfdb'] # 獲取 collection collection = db.test # collection = db['test'] View Code

增加一條記錄

添加一條記錄。

async def do_insert():document = {'name': 'zone','sex':'boy'}result = await db.test_collection.insert_one(document)print('result %s' % repr(result.inserted_id)) loop = asyncio.get_event_loop() loop.run_until_complete(do_insert()) View Code

批量增加記錄

添加結果如圖所暗示。

async def do_insert():result = await db.test_collection.insert_many([{'name': i, 'sex': str(i + 2)} for i in range(20)])print('inserted %d docs' % (len(result.inserted_ids),))loop = asyncio.get_event_loop() loop.run_until_complete(do_insert()) View Code

查找一條記錄

async def do_find_one():document = await db.test_collection.find_one({'name': 'zone'})pprint.pprint(document)loop = asyncio.get_event_loop() loop.run_until_complete(do_find_one()) View Code

查找多條記錄

查找記錄可以添加篩選條件。

async def do_find():cursor = db.test_collection.find({'name': {'$lt': 5}}).sort('i')for document in await cursor.to_list(length=100):pprint.pprint(document)loop = asyncio.get_event_loop() loop.run_until_complete(do_find())# 添加篩選條件,排序、跳過、限制返回結果數 async def do_find():cursor = db.test_collection.find({'name': {'$lt': 4}})# Modify the query before iteratingcursor.sort('name', -1).skip(1).limit(2)async for document in cursor:pprint.pprint(document)loop = asyncio.get_event_loop() loop.run_until_complete(do_find()) View Code

統計

async def do_count():n = await db.test_collection.count_documents({})print('%s documents in collection' % n)n = await db.test_collection.count_documents({'name': {'$gt': 1000}})print('%s documents where i > 1000' % n)loop = asyncio.get_event_loop() loop.run_until_complete(do_count()) View Code

替換

替換則是將除 id 以外的其他內容全部替換掉。

async def do_replace():coll = db.test_collectionold_document = await coll.find_one({'name': 'zone'})print('found document: %s' % pprint.pformat(old_document))_id = old_document['_id']result = await coll.replace_one({'_id': _id}, {'sex': 'hanson boy'})print('replaced %s document' % result.modified_count)new_document = await coll.find_one({'_id': _id})print('document is now %s' % pprint.pformat(new_document))loop = asyncio.get_event_loop() loop.run_until_complete(do_replace()) View Code

更新

更新指定字段,不會影響到其他內容。

async def do_update():coll = db.test_collectionresult = await coll.update_one({'name': 0}, {'$set': {'sex': 'girl'}})print('更新條數: %s ' % result.modified_count)new_document = await coll.find_one({'name': 0})print('更新結果為: %s' % pprint.pformat(new_document))loop = asyncio.get_event_loop() loop.run_until_complete(do_update()) View Code

刪除

刪除指定記錄。

async def do_delete_many():coll = db.test_collectionn = await coll.count_documents({})print('刪除前有 %s 條數據' % n)result = await db.test_collection.delete_many({'name': {'$gte': 10}})print('刪除后 %s ' % (await coll.count_documents({})))loop = asyncio.get_event_loop() loop.run_until_complete(do_delete_many()) View Code

后記

MongoDB 的騷操作就介紹到這里,后面會繼續寫 MySQL 和 Redis 的騷操作。盡請期待。

轉載于:https://www.cnblogs.com/hankleo/p/9941499.html

總結

以上是生活随笔為你收集整理的【转】Python操作MongoDB数据库的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。