MCPcopy Create free account
hub / github.com/NanmiCoder/MediaCrawler / MongoDBStoreBase

Class MongoDBStoreBase

database/mongodb_store_base.py:88–143  ·  view source on GitHub ↗

MongoDB storage base class: Provides common CRUD operations

Source from the content-addressed store, hash-verified

86
87
88class MongoDBStoreBase:
89 """MongoDB storage base class: Provides common CRUD operations"""
90
91 def __init__(self, collection_prefix: str):
92 """Initialize storage base class
93 Args:
94 collection_prefix: Platform prefix (xhs/douyin/bilibili, etc.)
95 """
96 self.collection_prefix = collection_prefix
97 self._connection = MongoDBConnection()
98
99 async def get_collection(self, collection_suffix: str) -> AsyncIOMotorCollection:
100 """Get collection: {prefix}_{suffix}"""
101 db = await self._connection.get_db()
102 collection_name = f"{self.collection_prefix}_{collection_suffix}"
103 return db[collection_name]
104
105 async def save_or_update(self, collection_suffix: str, query: Dict, data: Dict) -> bool:
106 """Save or update data (upsert)"""
107 try:
108 collection = await self.get_collection(collection_suffix)
109 await collection.update_one(query, {"$set": data}, upsert=True)
110 return True
111 except Exception as e:
112 utils.logger.error(f"[MongoDBStoreBase] Save failed ({self.collection_prefix}_{collection_suffix}): {e}")
113 return False
114
115 async def find_one(self, collection_suffix: str, query: Dict) -> Optional[Dict]:
116 """Query a single record"""
117 try:
118 collection = await self.get_collection(collection_suffix)
119 return await collection.find_one(query)
120 except Exception as e:
121 utils.logger.error(f"[MongoDBStoreBase] Find one failed ({self.collection_prefix}_{collection_suffix}): {e}")
122 return None
123
124 async def find_many(self, collection_suffix: str, query: Dict, limit: int = 0) -> List[Dict]:
125 """Query multiple records (limit=0 means no limit)"""
126 try:
127 collection = await self.get_collection(collection_suffix)
128 cursor = collection.find(query)
129 if limit > 0:
130 cursor = cursor.limit(limit)
131 return await cursor.to_list(length=None)
132 except Exception as e:
133 utils.logger.error(f"[MongoDBStoreBase] Find many failed ({self.collection_prefix}_{collection_suffix}): {e}")
134 return []
135
136 async def create_index(self, collection_suffix: str, keys: List[tuple], unique: bool = False):
137 """Create index: keys=[("field", 1)]"""
138 try:
139 collection = await self.get_collection(collection_suffix)
140 await collection.create_index(keys, unique=unique)
141 utils.logger.info(f"[MongoDBStoreBase] Index created on {self.collection_prefix}_{collection_suffix}")
142 except Exception as e:
143 utils.logger.error(f"[MongoDBStoreBase] Create index failed: {e}")

Callers 8

__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
__init__Method · 0.90
testMethod · 0.90

Calls

no outgoing calls

Tested by 1

testMethod · 0.72