標籤:upd class mode 關聯式資料庫 關係 dict als 資料 tab
Python Mongodb介面
MongoDB 是一個基於分布式檔案儲存體的資料庫。由 C++ 語言編寫。旨在為 WEB 應用提供可擴充的高效能資料儲存解決方案。
同時,MongoDB 是一個介於關聯式資料庫和非關聯式資料庫之間的產品,是NoSQL的優秀實現。
本文記錄使用PyMongo模組,用Python調用MongoDB
工具類實現
from pymongo import MongoClientmongodb_name = ‘dev_map‘client = MongoClient("mongodb://localhost:27017")mongua = client[mongodb_name]def timestamp(cls): import time return int(time.time())class ModelUtil(): @classmethod def add(cls, table_name, item): table = mongua[table_name] item["deleted"] = False ts = timestamp() item["created_time"] = ts item["updated_time"] = ts table.insert_one(item) @classmethod def delete(cls, table_name, conditions): item = cls.query(table_name, conditions) item["deleted"] = True cls.update(table_name, item) @classmethod def query(cls, table_name, conditions): table = mongua[table_name] item = table.find_one(conditions) return item @classmethod def exists(cls, table_name, conditions): table = mongua[table_name] item = table.find_one(conditions) return item is not None @classmethod def update(cls, table_name, item): table = mongua[table_name] item["updated_time"] = timestamp() table.save(item)
小結
使用MongDB,一方面可以像表格一樣訪問資料集合,另一方面,條目的類型可以是類似JSON的非結構化資料,而且正好對應Python中的dict,因此使用及其方便
Python Mongodb介面