一 安裝
pip install pymongo
二 python連接mongodb數據庫的前提
- 確保pymongo安裝完畢
- mongodb數據庫的服務器端(mongod)必須處於啟動狀態
三 連接mongodb
連接MongoDB我們需要使用PyMongo庫里面的MongoClient,一般來說傳入MongoDB的IP及端口即可,第一個參數為地址host,
第二個參數為端口port,端口如果不傳默認是27017。
- 方式一
client=pymongo.MongoClient(host='127.0.0.1',port=27017)
- 方式二
lient = pymongo.MongoClient('mongodb://localhost:27017/')
四 指定數據庫
- 特點:找不到數據庫,自動創建數據庫
- 代碼:
db=client.test #數據庫名為test
或者 db = client['test']
五 指定集合
- 特點:找不到集合,自動創建集合
- 代碼:
collection=db.student
或者collection = db['students']
六 插入數據
單條數據的插入
student = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' }
- 方式一:result=collection.insert(student)
- 方式二:result=collection.insert_one(student) #推薦使用
多條數據的插入
student2 = { '_id': '2', 'name': 'Jordan', 'age': 30, 'gender': 'male' } student3 = { '_id': '3', 'name': 'Mike', 'age': 20, 'gender': 'male' }
- 方式一:result=collection.insert([student2,student3])
- 方式二:result=collection.insert_many([student2,student3])#推薦使用
注意:官方推薦使用insert_one()和insert_many()方法將插入單條和多條記錄分開。
七 查詢
#根據系統生成的id查詢
from bson.objectid import ObjectId result = collection.find_one({'_id': ObjectId('593278c115c2602667ec6bae')}) print(result)
-
1 單條查詢
results = collection.find_one({'age': 20})
-
2 查詢結果返回多條
result_list=collection.find({'age':20}) print(result_list) for result in result_list: print(result['_id'])
2.2模糊查詢
'''
符號含義示例
$lt小於{'age': {'$lt': 20}}
$gt大於{'age': {'$gt': 20}}
$lte小於等於{'age': {'$lte': 20}}
$gte大於等於{'age': {'$gte': 20}}
$ne不等於{'age': {'$ne': 20}}
$in在范圍內{'age': {'$in': [20, 23]}}
$nin不在范圍內{'age': {'$nin': [20, 23]}}
'''
# 如果要查詢年齡大於20的數據,則寫法如下: results = collection.find({'age': {'$gt': 20}})
2.3 正則查詢
"""
符號含義示例示例含義
$regex匹配正則{'name': {'$regex': '^M.*'}}name以M開頭
$exists屬性是否存在{'name': {'$exists': True}}name屬性存在
$type類型判斷{'age': {'$type': 'int'}}age的類型為int
$mod數字模操作{'age': {'$mod': [5, 0]}}年齡模5余0
$text文本查詢{'$text': {'$search': 'Mike'}}text類型的屬性中包含Mike字符串
$where高級條件查詢{'$where': 'obj.fans_count == obj.follows_count'}自身粉絲數等於關注數
"""
# 另外還可以進行正則匹配查詢,例如查詢名字以M開頭的學生數據,示例如下: results = collection.find({'name': {'$regex': '^M.*'}})
3 其他
-
count = collection.find().count() #統計查詢返回的數量
-
results = collection.find().sort([('age',pymongo.ASCENDING),('name', pymongo.ASCENDING)]) #多條件排序
-
results = collection.find().sort('name', pymongo.ASCENDING).skip(2) #分頁提取數據
八 更新文檔
condition = {'name': 'Kevin'} student = collection.find_one(condition) student['age'] = 25 result = collection.update(condition, student) #在這里我們將name為Kevin的數據的年齡進行更新,首先指定查詢條件,然后將數據查詢出來,修改年齡, #之后調用update方法將原條件和修改后的數據傳入,即可完成數據的更新。
condition = {'age': {'$gt': 20}} result = collection.update_one(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count) # 在這里我們指定查詢條件為年齡大於20,然后更新條件為{'$inc': {'age': 1}},執行之后會講第一條符合條件的
數據年齡加1。
#更新多條數據
condition = {'age': {'$gt': 20}} result = collection.update_many(condition, {'$inc': {'age': 1}}) print(result) print(result.matched_count, result.modified_count)
九 刪除文檔
# 另外依然存在兩個新的推薦方法,delete_one()和delete_many()方法,示例如下: result = collection.delete_one({'name': 'Kevin'}) print(result) print(result.deleted_count) result = collection.delete_many({'age': {'$lt': 25}}) print(result.deleted_count)