mongodb.py 14 KB

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