一、MongoDB簡介
MongoDB是一種基於文檔的數據庫,在數據存儲方面與傳統的基於關係的數據庫有所不同。其主要優點包括擴展性強、易於水平擴展、支持非結構化數據等特點。同時,MongoDB 支持多種編程語言,如Python、Java等。MongoDB 是開源的,可在官方網站下載安裝包進行安裝使用。
二、MongoDB的基本操作
1. 連接 MongoDB 數據庫
可以使用官方提供的 Python 驅動 pymongo,連接 MongoDB 數據庫:
import pymongo client = pymongo.MongoClient(host='localhost', port=27017) db = client.test collection = db.students
2. 插入數據
可以使用 collection 的 insert() 方法插入一條數據:
student = { 'id': '20210001', 'name': 'Tom', 'age': 20, 'gender': 'male' } result = collection.insert_one(student) print(result)
3. 查詢數據
可以使用 find() 方法查詢數據:
result = collection.find_one({'name': 'Tom'}) print(result)
4. 更新數據
可以使用 update_one() 方法更新一條數據:
condition = {'name': 'Tom'} student = collection.find_one(condition) student['age'] = 21 result = collection.update_one(condition, {'$set': student}) print(result)
5. 刪除數據
可以使用 delete_one() 方法刪除一條數據:
condition = {'name': 'Tom'} result = collection.delete_one(condition) print(result)
三、數據模型與查詢
1. MongoDB 數據模型
MongoDB 的數據模型是基於文檔的存儲模型,也就是說,我們可以在一個文檔中存儲多個字段。MongoDB 的文檔是 BSON 格式的,BSON 是一種二進制形式的 JSON,其支持的數據類型包括數字、字符串、日期、對象等。下面是一個 MongoDB 文檔的示例:
{ "name": "Tom", "age": 20, "address": { "city": "Shanghai", "street": "Pudong" }, "scores": [85, 90, 95] }
2. MongoDB 查詢
MongoDB 的查詢語句支持多種操作符,如 $lt(小於)、$gt(大於)、$lte(小於等於)、$gte(大於等於)、$ne(不等於)等。下面是一個查詢示例:
result = collection.find({'age': {'$gt': 18}}) for res in result: print(res)
四、MongoDB高級應用
1. MongoDB索引
可以使用 create_index() 方法創建索引:
result = collection.create_index([('name', pymongo.ASCENDING)], unique=True)
2. MongoDB 聚合
MongoDB 支持聚合操作,可以使用 aggregate() 方法進行聚合操作:
result = collection.aggregate([ {'$match': {'gender': 'male'}}, {'$group': {'_id': '$age', 'count': {'$sum': 1}}} ]) for res in result: print(res)
3. MongoDB GridFS
MongoDB GridFS 是一種用於存儲大文件的機制,它允許我們將文件分塊存儲在 MongoDB 中,並提供了相應的接口進行讀取和寫入。下面是一個 GridFS 的示例:
from gridfs import GridFS fs = GridFS(db, collection='test') with open('test.jpg', 'rb') as f: file_id = fs.put(f.read(), filename='test.jpg') print(file_id)
五、總結
本文主要介紹了 MongoDB 的基本操作、數據模型和高級應用,包括索引、聚合和 GridFS 等。希望能對初學 MongoDB 的小夥伴們提供一些幫助。
原創文章,作者:WZXXT,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/324785.html