1. 程式人生 > >Python程式設計:mongodb的基本增刪改查操作

Python程式設計:mongodb的基本增刪改查操作

第一步當然是配置環境,啟動資料庫服務

引入模組

# -*- coding: utf-8 -*-

# @File    : pymongo_demo.py
# @Date    : 2018-06-02
# @Author  : Peng Shiyu

import pymongo

1、建立MongoDB的連線物件

# client = pymongo.MongoClient(host="localhost", port=27017)
client = pymongo.MongoClient('mongodb://localhost:27017/')

2、指定資料庫

# db = client["mydemo"]
db = client.mydemo

3、指定集合Collection物件

# collection = db["students"]
collection = db.students

4、插入資料

# 一條資料
student = {
    'id': '20170101',
    'name': '小明',
    'age': 22,
    'gender': '男性'
}

# result = collection.insert(student)
result = collection.insert_one(student)
print(result)  # <pymongo.results.InsertOneResult object at 0x1034e08c8>
print(result.inserted_id) # 5b1205b2d7696c4230dd9456 # 多條資料 student1 = { 'id': '20170101', 'name': 'Jordan', 'age': 20, 'gender': 'male' } student2 = { 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male' } # # # result = collection.insert([student1, student2]) result = collection.insert_many([student1, student2]) print(result) # <pymongo.results.InsertManyResult object at 0x1034e0748>
print(result.inserted_ids) # # [ObjectId('5b1205b2d7696c4230dd9457'), ObjectId('5b1205b2d7696c4230dd9458')]

5、查詢資料庫

# 查詢一條資料
result = collection.find_one({"name": "Mike"})
print(type(result))  # <class 'dict'>
print(result)
# {'_id': ObjectId('5b1204a3d7696c41c083d21e'),
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

# 通過_id屬性來查詢, 不存在則返回None
from bson.objectid import ObjectId
result = collection.find_one({'_id': ObjectId('5b1204a3d7696c41c083d21e')})
print(result)
# {'_id': ObjectId('5b1204a3d7696c41c083d21e'),
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

# 查詢多條資料, 返回一個生成器
results = collection.find({"age": 21})
print(results)  # <pymongo.cursor.Cursor object at 0x10133f160>
for result in results:
    print(result)
# {'_id': ObjectId('5b12055fd7696c4208deb74a'), 
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

# 條件查詢
results = collection.find({"age": {"$gt": 20}})
for result in results:
    print(result)
# {'_id': ObjectId('5b1209ccd7696c437c51d5bb'), 
# 'id': '20170101', 'name': '小明', 'age': 22, 'gender': '男性'}
# {'_id': ObjectId('5b1209ccd7696c437c51d5bd'), 
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}


# 正則匹配查詢
results = collection.find({"name": {"$regex": "^M.*"}})
for result in results:
    print(result)
# {'_id': ObjectId('5b1209ccd7696c437c51d5bd'),
# 'id': '20170202', 'name': 'Mike', 'age': 21, 'gender': 'male'}

比較符號

符號 表示 含義 示例
: = 等於 {“age”: 20}
$lt < 小於 {“age”: {“$lt”: 20}}
$gt > 大於 {“age”: {“$gt”: 20}}
$lte <= 小於等於 {“age”: {“$lte”: 20}}
$gte >= 大於等於 {“age”: {“$gte”: 20}}
$ne != 不等於 {“age”: {“$ne”: 20}}
$in in 範圍內 {“age”: {“$in”: [20, 30]}}
$nin not in 不在範圍內 {“age”: {“$nin”: [20, 30]}}

說明:
lt: less than
gt: great than
e: equal

功能符號

符號 含義 示例 示例說明
$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 高階條件查詢 {“name”: {“$where”: “obj.age==obj.count”}} 自身年齡等於自身數量

6、查詢計數

count = collection.find().count()
print(count)  # 3

7、資料排序

# 升序pymongo.ASCENDING 降序pymongo.DESCENDING
results = collection.find().sort("name", pymongo.ASCENDING)
print([result["name"] for result in results])
# ['Jordan', 'Mike', '小明']

8、資料的偏移

results = collection.find().sort('name', pymongo.ASCENDING).skip(2)
print([result['name'] for result in results])
# ['小明']

results = collection.find().sort('name', pymongo.ASCENDING).skip(1).limit(1)
print([result['name'] for result in results])
# ['Mike']

# 資料庫數量非常龐大的時候,不要使用大的偏移量
from bson.objectid import ObjectId
results = collection.find({'_id': {'$gt': ObjectId('5b1209ccd7696c437c51d5bb')}})
print([result['name'] for result in results])

9、更新資料庫

condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 25
# 全部用student字典替換
# result = collection.update(condition, student)
# 只更新student字典記憶體在的欄位
result = collection.update(condition, {'$set': student})
print(result)
# {'n': 1, 'nModified': 1, 'ok': 1.0, 'updatedExisting': True}

condition = {'name': 'Mike'}
student = collection.find_one(condition)
student['age'] = 26
result = collection.update_one(condition, {'$set': student})
print(result)
# <pymongo.results.UpdateResult object at 0x1034de708>

print(result.matched_count, result.modified_count)
# 1 1

condition = {'age': {'$gt': 20}}
result = collection.update_one(condition, {'$inc': {'age': 1}})
print(result)
# <pymongo.results.UpdateResult object at 0x1034e8588>
print(result.matched_count, result.modified_count)
# 1 1

10、資料刪除

result = collection.remove({'name': 'Jordan'})
print(result)

# 刪除一條
result = collection.delete_one({'name': 'Kevin'})
print(result)
print(result.deleted_count)
result = collection.delete_many({'age': {'$lt': 25}})
print(result.deleted_count)

# 刪除多條
result = collection.delete_many({'name': 'Kevin'})