1. 程式人生 > 資料庫 >淺析Python與Mongodb資料庫之間的操作方法

淺析Python與Mongodb資料庫之間的操作方法

MongoDB 是目前最流行的 NoSQL 資料庫之一,使用的資料型別 BSON(類似 JSON)。

1. 安裝Mongodb和pymongo

Mongodb的安裝和配置

Mongodb的安裝教程請網上搜索,安裝完成後,進行以下配置過程:

1.1 建立目錄,該目錄為Mongodb資料檔案的存放目錄:

*注: 本人使用的不是root使用者,所以修改目錄的擁有者. *

sudo mkdir /data
sudo chown -R python:python /data
mkdir /data/db

1.2 分別執行命令:

第一條命令為指定埠和儲存路徑,第二條為執行mongodb資料庫.

mongod --port 27017 --dbpath /data/db
mongo --port 27017

1.3 安裝pymongo

sudo pip3 install pymongo

2. 連線資料庫、指定資料庫、指定集合、插入資料:

mongodb儲存資料以鍵值形式,因此在Python中使用欄位插入資料.

import pymongo
#連線mongodb
client = pymongo.MongoClient('mongodb://localhost:27017/')
#指定資料庫
db = client.test4
#指定集合
collection = db.students
#資料
student1 = {
 'id': '201801','name': 'Jack','age': 20,'gender': 'male'
}
student2 = {
 'id': '201802','name': 'Tom','age': 22,'gender': 'male'
}
student3 = {
 'id': '201803','name': 'Rose','age': 21,'gender': 'female'
}
student4 = {
 'id': '201804','name': 'Mike','gender': 'female'
}
student5 = {
 'id': '201805','name': 'Ray','gender': 'female'
}
student6 = {
 'id': '201806','name': 'Alan','gender': 'male'
}
#插入一條資料
result1 = collection.insert_one(student1)
print(result1)
print(result1.inserted_id)
# #插入多條資料
result2 = collection.insert_many([student2,student3,student4,student5,student6])
print(result2)
print(result2.inserted_ids)

執行結果:

insert方法:

5b3a1942971951218d41c02b
[ObjectId('5b3a1942971951218d41c02c'),ObjectId('5b3a1942971951218d41c02d')]

官方推薦:

<pymongo.results.InsertOneResult object at 0x7fa4cc363ec8>
5b3a1942971951218d41c02e
<pymongo.results.InsertManyResult object at 0x7fa4cc363f08>
[ObjectId('5b3a1942971951218d41c02f'),ObjectId('5b3a1942971951218d41c030')]

3. 查詢、計數、排序、偏移:

import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#查詢一條資料
print('單條資料','='*50)
result = collection.find_one({'name': 'Jack'})
print(result)
print('多條資料','='*50)
#查詢多條資料
for res in collection.find({'age': {'$mod': [5,0]}}):
 print(res)
#計數
print('計數','='*50)
count = collection.find({'age': {'$mod': [5,0]}}).count()
print(count)
#排序
print('排序','='*50)
results = collection.find().sort('name',pymongo.ASCENDING) #升序,pymongo.DESCENDING為降序
print([result['name'] for result in results])
#偏移
print('偏移',pymongo.ASCENDING).skip(2) #偏移2位,忽略前兩個資料
print([result['name'] for result in results])
results = collection.find().sort('name',pymongo.ASCENDING).skip(2).limit(2) #只輸出2個數據
print([result['name'] for result in results])
find({‘age': {'$mod': [5,0]}}): 表示查詢年齡取餘5餘0的值. 還有很多比較符號,請百度.

執行結果:

單條資料 ==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'),'id': '201801','gender': 'male'}
多條資料 ==================================================
{'_id': ObjectId('5b3a1942971951218d41c02b'),'gender': 'male'}
{'_id': ObjectId('5b3a1942971951218d41c02e'),'id': '201804','gender': 'female'}
{'_id': ObjectId('5b3a1942971951218d41c02f'),'id': '201805','gender': 'female'}
計數 ==================================================
3
排序 ==================================================
['Alan','Jack','Mike','Ray','Rose','Tom']
偏移 ==================================================
['Mike','Tom']
['Mike','Ray']

4. 更新:

4.1 不使用$set更新資料:

import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#修改
condition = {'name': 'Jack'}
student = collection.find_one(condition) #獲得滿足condition的資料
print('更新前: ',student)
student['age'] = 22 #修改年齡
result = collection.update(condition,student) #將修改後的student替換condition
print('更新後',collection.find_one(condition))
#更新的返回值
print(result) #ok=1代表執行成功,nModified代表影響的條數

執行結果:

更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'),'gender': 'male'}
更新後 {'_id': ObjectId('5b3a1942971951218d41c02b'),'gender': 'male'}
{'ok': 1,'nModified': 1,'n': 1,'updatedExisting': True}

4.2 使用$set更新資料:

import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#使用$set更新
condition = {'name': 'Jack'}
student = collection.find_one(condition) #獲得滿足condition的資料
print('更新前: ',student)
student['age'] = 23 #修改年齡
result = collection.update(condition,{'$set': student}) #將修改後的student替換condition,$set為重點
print('更新後','age': 23,'updatedExisting': True}

比較使用和不適用$set更新資料,發現此時並沒有什麼區別.

下面介紹區別所在:

4.3 區別

import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#使用和不使用$set更新的區別
print('使用: ')
condition = {'name': 'Jack'}
student = collection.find_one(condition) #獲得滿足condition的資料
print('更新前: ',student)
student = {
 'id': '201803','gender': 'female','mother': "Jack's mother"
}
result = collection.update(condition,{'$set': student}) #將修改後的student替換condition
print('更新後',nModified代表影響的條數
#分割線
print()
print('='*20,'分割線','='*20)
print()
print('不使用: ')
condition = {'name': 'Jack'}
student = collection.find_one(condition) #獲得滿足condition的資料
print('更新前: ','father': "Jack's father"
}
result = collection.update(condition,nModified代表影響的條數

執行結果:

使用:

更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'),'id': '201803','mother': "Jack's mother"}
{'ok': 1,'updatedExisting': True}

==================== 分割線 ====================

不使用: 
更新前: {'_id': ObjectId('5b3a1942971951218d41c02b'),'mother': "Jack's mother"}
更新後 {'_id': ObjectId('5b3a1942971951218d41c02b'),'father': "Jack's father"}
{'ok': 1,'updatedExisting': True}

分析上面執行結果,可以發現使用$set時,若更新資料有原資料沒有的欄位,則將該欄位加到原資料上(上例為新增了mother欄位),而不會刪除任何欄位. 相反,若不使用set時,將從原資料中刪除更新資料沒有的欄位,再加上新增欄位(上例為刪除了mother欄位,新增了father欄位. 也可以理解為將原資料完全替換為更新資料)

4.4 update_one和update_many的區別:

import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#官方推薦使用
#update_one和update_many的區別
print('update_one: ')
condition = {'age': {'$gt': 20}}
result = collection.update_one(condition,{'$inc': {'age': 1}})
print(result)
print(result.matched_count,result.modified_count)
#分割線
print()
print('='*20,'='*20)
print()
print('update_many: ')
condition = {'age': {'$gt': 20}}
result = collection.update_many(condition,result.modified_count)

執行結果:

update_one: 
<pymongo.results.UpdateResult object at 0x7f6cace0f9c8>
1 1
==================== 分割線 ====================
update_many: 
<pymongo.results.UpdateResult object at 0x7f6cace0fa88>
3 3
12345678910
{‘age': {'$gt': 20}}為查詢年齡大於20的,{‘inc': {‘age': 1}}為將年齡+1

5. 刪除:

import pymongo
from bson.objectid import ObjectId
client = pymongo.MongoClient('mongodb://localhost:27017/')
db = client.test4
collection = db.students
#刪除
result = collection.remove({'name': 'Jack'})
print(result)
#推薦使用
result = collection.delete_one({'age': {'$gt': 20}})
print(result.deleted_count)
result = collection.delete_many({'age': {'$gt': 20}})
print(result.deleted_count)

執行結果:

{'ok': 1,'n': 1}
1
2

6. 其他

除了上述常用的之外,還包括find_one_and_delete()查詢後刪除、find_one_and_replace()查詢後替換,有興趣可以百度深入瞭解.

總結

以上所述是小編給大家介紹的Python與Mongodb資料庫之間的操作方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對我們網站的支援!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!