一、MongoDB是什麼?
MongoDB是一個非關係型、面向文檔的資料庫管理系統,以C++語言編寫,被廣泛應用於現代Web應用程序的開發中。
與傳統的關係型資料庫不同,MongoDB是一個完全面向對象的資料庫,使用JSON形式來存儲數據。它採用了靈活的文檔模型,不需要預定義表結構,數據可以非常容易地嵌入,支持多種數據類型,包括二進位、數組和嵌入的文檔。
MongoDB架構的特點是支持水平擴展,具有高性能以及高可用性。
二、為什麼要使用MongoDB?
MongoDB的優點之一是強大的查詢性能。由於存儲數據以文檔形式,「查詢過濾器」可以更輕鬆地訪問數據,甚至可以跨多個文檔嵌套查詢。
MongoDB還可用於處理非結構化數據,例如,在未知的數據類型或帶有大量嵌套屬性的數據集中。
另一個優點是高可用性。MongoDB可以將數據複製到多個節點以實現「副本集群」,從而使故障轉移更加容易,同時提供快速的讀取副本方式,增加應用程序的可擴展性。
最後,MongoDB的性能比許多其他資料庫更好。由於它是一個跨平台系統,並且可以定製修改,因此可以根據項目的要求定製開發過程。
三、基本MongoDB查詢操作
在MongoDB中,可以使用Mongo shell、Compass等不同工具進行查詢操作。這裡使用Mongo shell作為演示。
1. 插入
db..insertOne() # 插入一條記錄,如果集合二合一不存在,會自動創建
db..insertMany() # 插入多條記錄,返回ID列表
2. 查詢
db..find(, ) # 查詢數據
db..findOne(, ) # 查詢一條數據
3. 更新
db..updateOne(, , ) # 更新一條數據
db..updateMany(, , ) # 更新多條數據
4. 刪除
db..deleteOne() # 刪除一條數據
db..deleteMany() # 刪除多條數據
四、使用MongoDB的代碼示例
安裝MongoDB。進入官網(https://www.mongodb.com/download-center/community),選擇合適的版本進行下載。
1. 插入
mongodb_test.py的代碼如下:
from pymongo import MongoClient
client = MongoClient() # 創建MongoDB客戶端
db = client["test_db"] # 獲取資料庫,如果不存在則自動創建
collection = db["test_collection"] # 獲取集合,如果不存在則自動創建
# 插入一條記錄
post = {"author": "Peter", "text": "My first blog post!", "tags": ["MongoDB", "Python", "Pymongo"]}
result = collection.insert_one(post)
print(result.inserted_id)
# 插入多條記錄
new_posts = [
{"author": "Mike", "text": "Another post!", "tags": ["bulk", "insert"]},
{"author": "Eliot", "title": "MongoDB is fun", "text": "and pretty easy too!", "date": datetime.datetime.utcnow()}
]
result = collection.insert_many(new_posts)
print(result.inserted_ids)
運行代碼後,會輸出每次插入操作的ID號。
2. 查詢
mongodb_test.py的代碼如下:
from pymongo import MongoClient
client = MongoClient() # 創建MongoDB客戶端
db = client["test_db"] # 獲取資料庫,如果不存在則自動創建
collection = db["test_collection"] # 獲取集合,如果不存在則自動創建
# 查詢一條數據
result = collection.find_one({"author": "Peter"})
print(result)
# 查詢多條數據
results = collection.find({"author": "Peter"})
for result in results:
print(result)
3. 更新
mongodb_test.py的代碼如下:
from pymongo import MongoClient
client = MongoClient() # 創建MongoDB客戶端
db = client["test_db"] # 獲取資料庫,如果不存在則自動創建
collection = db["test_collection"] # 獲取集合,如果不存在則自動創建
# 更新一條數據
result = collection.update_one({"text": "My first blog post!"}, {"$set": {"text": "My second blog post!"}})
print("更新了", result.modified_count, "條記錄。")
# 更新多條數據
result = collection.update_many({"author": "Mike"}, {"$set": {"author": "Eric"}})
print("更新了", result.modified_count, "條記錄。")
4. 刪除
mongodb_test.py的代碼如下:
from pymongo import MongoClient
client = MongoClient() # 創建MongoDB客戶端
db = client["test_db"] # 獲取資料庫,如果不存在則自動創建
collection = db["test_collection"] # 獲取集合,如果不存在則自動創建
# 刪除一條數據
result = collection.delete_one({"author": "Peter"})
print("刪除了", result.deleted_count, "條記錄。")
# 刪除多條數據
result = collection.delete_many({"author": "Mike"})
print("刪除了", result.deleted_count, "條記錄。")
五、結論
MongoDB是一種非常靈活的NoSQL資料庫,可以用於各種現代Web應用程序的開發,具有高性能和高可用性。通過學習基本查詢操作,可以更加了解MongoDB的功能和使用方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/206209.html