MongoDB 服務(wù)器對接指南
1. 環(huán)境準備
MongoDB 安裝:確保你的服務(wù)器上已安裝 MongoDB,MongoDB 服務(wù)正在運行。
Python 環(huán)境:確保 Python 環(huán)境已經(jīng)安裝,因為以下示例代碼將使用 Python 進行連接。
2. 連接 MongoDB
以下是一個使用 Python 和pymongo庫連接到 MongoDB 服務(wù)器的示例代碼:
- from pymongo import MongoClient
- MongoDB 服務(wù)器地址
- mongo_host = '127.0.0.1'
- mongo_port = 27017 # 默認端口
- 創(chuàng)建 MongoClient 實例
- client = MongoClient(mongo_host, mongo_port)
- 選擇數(shù)據(jù)庫
- db = client['your_database_name']
- 選擇集合(如果不存在,MongoDB 會自動創(chuàng)建)
- collection = db['your_collection_name']
- 檢查連接是否成功
- print("MongoDB connection is successful.")
3. 數(shù)據(jù)操作
以下是一些基本的數(shù)據(jù)庫操作示例:
3.1 插入數(shù)據(jù)
- 插入單條數(shù)據(jù)
- document = {"name": "John", "age": 30}
- result = collection.insert_one(document)
- print("Inserted document id:", result.inserted_id)
- 插入多條數(shù)據(jù)
- documents = [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 35}]
- result = collection.insert_many(documents)
- print("Inserted document ids:", result.inserted_ids)
3.2 查詢數(shù)據(jù)
- 查詢所有數(shù)據(jù)
- results = collection.find()
- for result in results:
- print(result)
- 查詢特定條件的數(shù)據(jù)
- query = {"age": 30}
- results = collection.find(query)
- for result in results:
- print(result)
3.3 更新數(shù)據(jù)
- 更新單條數(shù)據(jù)
- update_result = collection.update_one({"name": "John"}, {"$set": {"age": 31}})
- print("Modified count:", update_result.modified_count)
- 更新多條數(shù)據(jù)
- update_result = collection.update_many({"age": 25}, {"$set": {"age": 26}})
- print("Modified count:", update_result.modified_count)
3.4 刪除數(shù)據(jù)
- 刪除單條數(shù)據(jù)
- delete_result = collection.delete_one({"name": "Alice"})
- print("Deleted count:", delete_result.deleted_count)
- 刪除多條數(shù)據(jù)
- delete_result = collection.delete_many({"age": 26})
- print("Deleted count:", delete_result.deleted_count)
4. 關(guān)閉連接
在完成所有數(shù)據(jù)庫操作后,應(yīng)該關(guān)閉數(shù)據(jù)庫連接:
- client.close()
- print("MongoDB connection is closed.")
5. 注意事項
確保數(shù)據(jù)庫用戶具有適當(dāng)?shù)臋?quán)限。
避免在代碼中硬編碼敏感信息,如數(shù)據(jù)庫用戶名和密碼。
對于生產(chǎn)環(huán)境,考慮使用 SSL 連接以提高安全性。
通過以上步驟,你可以成功對接 MongoDB 服務(wù)器并進行基本的數(shù)據(jù)操作,如果需要更高級的功能或配置,請參考 MongoDB 官方文檔。