mongodb.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on 2021-04-18 14:12:21
  4. ---------
  5. @summary: 操作mongo数据库
  6. ---------
  7. @author: Mkdir700
  8. @email: mkdir700@gmail.com
  9. """
  10. import re
  11. from typing import List, Dict, Optional
  12. from urllib import parse
  13. import pymongo
  14. from pymongo import MongoClient
  15. from pymongo.collection import Collection
  16. from pymongo.database import Database
  17. from pymongo.errors import DuplicateKeyError, BulkWriteError
  18. import feapder.setting as setting
  19. from feapder.utils.log import log
  20. class MongoDB:
  21. def __init__(
  22. self,
  23. ip=None,
  24. port=None,
  25. db=None,
  26. user_name=None,
  27. user_pass=None,
  28. url=None,
  29. **kwargs,
  30. ):
  31. if url:
  32. self.client = MongoClient(url, **kwargs)
  33. else:
  34. if not ip:
  35. ip = setting.MONGO_IP
  36. if not port:
  37. port = setting.MONGO_PORT
  38. if not db:
  39. db = setting.MONGO_DB
  40. if not user_name:
  41. user_name = setting.MONGO_USER_NAME
  42. if not user_pass:
  43. user_pass = setting.MONGO_USER_PASS
  44. self.client = MongoClient(
  45. host=ip, port=port, username=user_name, password=user_pass
  46. )
  47. self.db = self.get_database(db)
  48. # 缓存索引信息
  49. self.__index__cached = {}
  50. @classmethod
  51. def from_url(cls, url, **kwargs):
  52. """
  53. Args:
  54. url: mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  55. 参考:http://mongodb.github.io/mongo-java-driver/3.4/javadoc/com/mongodb/MongoClientURI.html
  56. **kwargs:
  57. Returns:
  58. """
  59. url_parsed = parse.urlparse(url)
  60. db_type = url_parsed.scheme.strip()
  61. if db_type != "mongodb":
  62. raise Exception(
  63. "url error, expect mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]], but get {}".format(
  64. url
  65. )
  66. )
  67. return cls(url=url, **kwargs)
  68. def get_database(self, database, **kwargs) -> Database:
  69. """
  70. 获取数据库对象
  71. @param database: 数据库名
  72. @return:
  73. """
  74. return self.client.get_database(database, **kwargs)
  75. def get_collection(self, coll_name, **kwargs) -> Collection:
  76. """
  77. 根据集合名获取集合对象
  78. @param coll_name: 集合名
  79. @return:
  80. """
  81. return self.db.get_collection(coll_name, **kwargs)
  82. def find(
  83. self, coll_name: str, condition: Optional[Dict] = None, limit: int = 0, **kwargs
  84. ) -> List[Dict]:
  85. """
  86. @summary:
  87. 无数据: 返回[]
  88. 有数据: [{'_id': 'xx', ...}, ...]
  89. ---------
  90. @param coll_name: 集合名(表名)
  91. @param condition: 查询条件
  92. @param limit: 结果数量
  93. @param kwargs:
  94. 更多参数 https://docs.mongodb.com/manual/reference/command/find/#command-fields
  95. ---------
  96. @result:
  97. """
  98. condition = {} if condition is None else condition
  99. command = {"find": coll_name, "filter": condition, "limit": limit}
  100. command.update(kwargs)
  101. result = self.run_command(command)
  102. cursor = result["cursor"]
  103. cursor_id = cursor["id"]
  104. dataset = cursor["firstBatch"]
  105. while True:
  106. if cursor_id == 0:
  107. break
  108. result = self.run_command(
  109. {
  110. "getMore": cursor_id,
  111. "collection": coll_name,
  112. "batchSize": kwargs.get("batchSize", 100),
  113. }
  114. )
  115. cursor = result["cursor"]
  116. cursor_id = cursor["id"]
  117. dataset.extend(cursor["nextBatch"])
  118. return dataset
  119. def add(
  120. self,
  121. coll_name,
  122. data: Dict,
  123. replace=False,
  124. update_columns=(),
  125. update_columns_value=(),
  126. insert_ignore=False,
  127. ):
  128. """
  129. 添加单条数据
  130. Args:
  131. coll_name: 集合名
  132. data: 单条数据
  133. replace: 唯一索引冲突时直接覆盖旧数据,默认为False
  134. update_columns: 更新指定的列(如果数据唯一索引冲突,则更新指定字段,如 update_columns = ["name", "title"]
  135. update_columns_value: 指定更新的字段对应的值, 不指定则用数据本身的值更新
  136. insert_ignore: 索引冲突是否忽略 默认False
  137. Returns: 插入成功的行数
  138. """
  139. affect_count = 1
  140. collection = self.get_collection(coll_name)
  141. try:
  142. collection.insert_one(data)
  143. except DuplicateKeyError as e:
  144. # 存在则更新
  145. if update_columns:
  146. if not isinstance(update_columns, (tuple, list)):
  147. update_columns = [update_columns]
  148. condition = self.__get_update_condition(
  149. coll_name, data, e.details.get("errmsg")
  150. )
  151. # 更新指定的列
  152. if update_columns_value:
  153. # 使用指定的值更新
  154. doc = {
  155. key: value
  156. for key, value in zip(update_columns, update_columns_value)
  157. }
  158. else:
  159. # 使用数据本身的值更新
  160. doc = {key: data[key] for key in update_columns}
  161. collection.update_one(condition, {"$set": doc})
  162. # 覆盖更新
  163. elif replace:
  164. condition = self.__get_update_condition(
  165. coll_name, data, e.details.get("errmsg")
  166. )
  167. # 替换已存在的数据
  168. collection.replace_one(condition, data)
  169. elif not insert_ignore:
  170. raise e
  171. return affect_count
  172. def add_batch(
  173. self,
  174. coll_name: str,
  175. datas: List[Dict],
  176. replace=False,
  177. update_columns=(),
  178. update_columns_value=(),
  179. condition_fields: dict = None,
  180. ):
  181. """
  182. 批量添加数据
  183. Args:
  184. coll_name: 集合名
  185. datas: 数据 [{'_id': 'xx'}, ... ]
  186. replace: 唯一索引冲突时直接覆盖旧数据,默认为False
  187. update_columns: 更新指定的列(如果数据的唯一索引存在,则更新指定字段,如 update_columns = ["name", "title"]
  188. update_columns_value: 指定更新的字段对应的值, 不指定则用数据本身的值更新
  189. condition_fields: 用于条件查找的字段,不指定则用索引冲突中的字段查找
  190. Returns: 添加行数,不包含更新
  191. """
  192. add_count = 0
  193. if not datas:
  194. return add_count
  195. collection = self.get_collection(coll_name)
  196. if not isinstance(update_columns, (tuple, list)):
  197. update_columns = [update_columns]
  198. try:
  199. add_count = len(datas)
  200. collection.insert_many(datas, ordered=False)
  201. except BulkWriteError as e:
  202. write_errors = e.details.get("writeErrors")
  203. for error in write_errors:
  204. if error.get("code") == 11000:
  205. # 数据重复
  206. # 获取重复的数据
  207. data = error.get("op")
  208. def get_condition():
  209. # 获取更新条件
  210. if condition_fields:
  211. condition = {
  212. condition_field: data[condition_field]
  213. for condition_field in condition_fields
  214. }
  215. else:
  216. # 根据重复的值获取更新条件
  217. condition = self.__get_update_condition(
  218. coll_name, data, error.get("errmsg")
  219. )
  220. return condition
  221. if update_columns:
  222. # 更新指定的列
  223. if update_columns_value:
  224. # 使用指定的值更新
  225. doc = {
  226. key: value
  227. for key, value in zip(
  228. update_columns, update_columns_value
  229. )
  230. }
  231. else:
  232. # 使用数据本身的值更新
  233. doc = {key: data.get(key) for key in update_columns}
  234. collection.update_one(get_condition(), {"$set": doc})
  235. add_count -= 1
  236. elif replace:
  237. # 覆盖更新
  238. collection.replace_one(get_condition(), data)
  239. add_count -= 1
  240. else:
  241. # log.error(error)
  242. add_count -= 1
  243. return add_count
  244. def count(self, coll_name, condition: Optional[Dict], limit=0, **kwargs):
  245. """
  246. 计数
  247. @param coll_name: 集合名
  248. @param condition: 查询条件
  249. @param limit: 限制数量
  250. @param kwargs:
  251. ----
  252. command = {
  253. count: <collection or view>,
  254. query: <document>,
  255. limit: <integer>,
  256. skip: <integer>,
  257. hint: <hint>,
  258. readConcern: <document>,
  259. collation: <document>,
  260. comment: <any>
  261. }
  262. https://docs.mongodb.com/manual/reference/command/count/#mongodb-dbcommand-dbcmd.count
  263. @return: 数据数量
  264. """
  265. command = {"count": coll_name, "query": condition, "limit": limit, **kwargs}
  266. result = self.run_command(command)
  267. return result["n"]
  268. def update(self, coll_name, data: Dict, condition: Dict, upsert: bool = False):
  269. """
  270. 更新
  271. Args:
  272. coll_name: 集合名
  273. data: 单条数据 {"xxx":"xxx"}
  274. condition: 更新条件 {"_id": "xxxx"}
  275. upsert: 数据不存在则插入,默认为 False
  276. Returns: True / False
  277. """
  278. try:
  279. collection = self.get_collection(coll_name)
  280. collection.update_one(condition, {"$set": data}, upsert=upsert)
  281. except Exception as e:
  282. log.error(
  283. """
  284. error:{}
  285. condition: {}
  286. """.format(
  287. e, condition
  288. )
  289. )
  290. return False
  291. else:
  292. return True
  293. def delete(self, coll_name, condition: Dict) -> bool:
  294. """
  295. 删除
  296. Args:
  297. coll_name: 集合名
  298. condition: 查找条件
  299. Returns: True / False
  300. """
  301. try:
  302. collection = self.get_collection(coll_name)
  303. collection.delete_one(condition)
  304. except Exception as e:
  305. log.error(
  306. """
  307. error:{}
  308. condition: {}
  309. """.format(
  310. e, condition
  311. )
  312. )
  313. return False
  314. else:
  315. return True
  316. def run_command(self, command: Dict):
  317. """
  318. 运行指令
  319. 参考文档 https://www.geek-book.com/src/docs/mongodb/mongodb/docs.mongodb.com/manual/reference/command/index.html
  320. @param command:
  321. @return:
  322. """
  323. return self.db.command(command)
  324. def create_index(self, coll_name, keys, unique=True):
  325. collection = self.get_collection(coll_name)
  326. _keys = [(key, pymongo.ASCENDING) for key in keys]
  327. collection.create_index(_keys, unique=unique)
  328. def get_index(self, coll_name):
  329. return self.get_collection(coll_name).index_information()
  330. def drop_collection(self, coll_name):
  331. return self.db.drop_collection(coll_name)
  332. def get_index_key(self, coll_name, index_name):
  333. """
  334. 获取参与索引的key
  335. Args:
  336. index_name: 索引名
  337. Returns:
  338. """
  339. cache_key = f"{coll_name}:{index_name}"
  340. if cache_key in self.__index__cached:
  341. return self.__index__cached.get(cache_key)
  342. index = self.get_index(coll_name)
  343. index_detail = index.get(index_name)
  344. if not index_detail:
  345. errmsg = f"not found index {index_name} in collection {coll_name}"
  346. raise Exception(errmsg)
  347. index_keys = [val[0] for val in index_detail.get("key")]
  348. self.__index__cached[cache_key] = index_keys
  349. return index_keys
  350. def __get_update_condition(
  351. self, coll_name: str, data: dict, duplicate_errmsg: str
  352. ) -> dict:
  353. """
  354. 根据索引冲突的报错信息 获取更新条件
  355. Args:
  356. duplicate_errmsg: E11000 duplicate key error collection: feapder.test index: a_1_b_1 dup key: { : 1, : "你好" }
  357. data: {"a": 1, "b": "你好", "c": "嘻嘻"}
  358. Returns: {"a": 1, "b": "你好"}
  359. """
  360. index_name = re.search(r"index: (\w+)", duplicate_errmsg).group(1)
  361. index_keys = self.get_index_key(coll_name, index_name)
  362. condition = {key: data.get(key) for key in index_keys}
  363. return condition
  364. def __getattr__(self, name):
  365. return getattr(self.db, name)