1. 程式人生 > >資料庫的 N 多騷操作了解一下?

資料庫的 N 多騷操作了解一下?

640?wx_fmt=gif

640?wx_fmt=jpeg

作者 | zone7
責編 | 郭   芮

本文來介紹一下 Python 與 MongoDB 資料庫的使用,走起!



640?wx_fmt=png

MongoDB GUI 工具



首先介紹一款 MongoDB 的 GUI 工具 Robo 3T,初學 MongoDB 用這個來檢視資料真的很爽。可以即時看到資料的增刪改查,不用操作命令列來檢視。


640?

640?


操作介面圖



640?wx_fmt=png

PyMongo(同步)



PyMongo 是一個同步操作的資料儲存庫。可能大家都對 PyMongo 比較熟悉了,這裡就簡單介紹它的增刪改查等操作。


連線


# 普通連線
client = MongoClient('localhost'27017)
client = MongoClient('mongodb://localhost:27017/')
#
# 密碼連線
client = MongoClient('mongodb://username:[email protected]:27017/dbname')
db = client.zfdb
# db = client['zfdb']

test = db.test



# 增加一條記錄
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)



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



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




# 查詢多條記錄
pprint.pprint(test.find())

# 新增查詢條件
pprint.pprint(test.find({"sex""boy"}).sort("name"))


聚合


如果你是我的老讀者,那麼你肯定知道我之前的騷操作,就是用爬蟲爬取資料之後,用聚合統計結合視覺化圖表進行資料展示。


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)


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


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


聚合效果圖示例:


640?
Python 工作年限要求

640?

Python 學歷要求



640?wx_fmt=png

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:[email protected]:27017/dbname')
# 獲取資料庫
db = client.zfdb
# db = client['zfdb']
# 獲取 collection
collection = db.test
# collection = db['test']


增加一條記錄


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())

640?


批量增加記錄


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())

640?


查詢一條記錄


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())

640?


查詢多條記錄


查詢記錄可以新增篩選條件。


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 iterating
    cursor.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())

640?


統計


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())

640?


替換


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


async def do_replace():
    coll = db.test_collection
    old_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())

640?


更新


更新指定欄位,不會影響到其他內容。


async def do_update():
    coll = db.test_collection
    result = 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())

640?


刪除


刪除指定記錄。


async def do_delete_many():
    coll = db.test_collection
    n = 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())

640?


MongoDB 的騷操作就介紹到這裡,希望對你有所幫助。

作者:zone7,一隻愛折騰的後端攻城獅,愛寫作愛分享。

宣告:本文首發於公眾號 zone7,作者投稿,版權歸對方所有。



 熱 文 推 薦  

☞ 「傻瓜」才能寫出好程式碼!

☞ 漫畫 | 從搬家到容器技術 Docker 應用場景解析

☞ Hacker News 12 月招聘趨勢:React 已連續霸榜 19 個月

☞ 從傾家蕩產到身價百億,這個85後只用了8年

☞ 難逃寒冬裁員的“大追殺”,30 歲女碼農該何去何從?

☞ OpenStack 2018 年終盤點

☞ 拼多多黃崢給陸奇“兼職”,欲挖掘這類AI人才

☞ 老程式設計師肺腑忠告:千萬別一輩子靠技術生存!


  

print_r('點個好看吧!');
var_dump('點個好看吧!');
NSLog(@"點個好看吧!");
System.out.println("點個好看吧!");
console.log("點個好看吧!");
print("點個好看吧!");
printf("點個好看吧!\n");
cout << "點個好看吧!" << endl;
Console.WriteLine("點個好看吧!");
fmt.Println("點個好看吧!");
Response.Write("點個好看吧!");
alert("點個好看吧!")
echo "點個好看吧!"

640?wx_fmt=gif點選“閱讀原文”,開啟 CSDN App 閱讀更貼心!

640?wx_fmt=png 喜歡就點選“好看”吧!