xmongo.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. # update: 2022-3-30-15
  2. """
  3. $eq 等于
  4. $ne 不等
  5. $in []
  6. db.collection.find({ field: { $not: { $in: [value1, value2, value3] } } })
  7. $regex 模糊查找
  8. (>) 大于 - $gt
  9. (<) 小于 - $lt
  10. (>=) 大于等于 - $gte
  11. (<= ) 小于等于 - $lte
  12. pip install pymongo==3.11.2 -i https://pypi.tuna.tsinghua.edu.cn/simple
  13. """
  14. from pymongo import MongoClient, TEXT
  15. from bson.objectid import ObjectId
  16. class Client(MongoClient):
  17. def __init__(self, host='sri-thirdparty-mongo', port=27017, database='vms', username='admin', password='admin'):
  18. """
  19. 内部访问:
  20. host: sri-thirdparty-mongo
  21. port: 27017
  22. 远程访问:
  23. host: 118.190.217.96、192.168.20.162
  24. port: 7030
  25. """
  26. super().__init__(f'mongodb://{username}:{password}@{host}:{port}')
  27. self.db = self[database]
  28. def run_command(self, command=None, command_type='dict', use_admin=False):
  29. """
  30. Command:
  31. print(self.db.command('serverStatus'))
  32. print(self.db.command('dbstats'))
  33. print(self['admin'].command('listDatabases', 1)) # 查看数据库信息
  34. print(self['admin'].command({'setParameter': 1, 'internalQueryExecMaxBlockingSortBytes': 52428800})) # 设置排序内存限制
  35. print(self['admin'].command({'getParameter': 1, 'internalQueryExecMaxBlockingSortBytes': 1})) # 查询排序内存限制
  36. print(self.db.command('collstats', 'WorkFlowPlugin')) # 查看表信息
  37. print(self.db.command({'collStats': 'WorkFlowPlugin'})) # 查看表信息
  38. Usage:
  39. self.run_command(
  40. command={'setParameter': 1, 'internalQueryExecMaxBlockingSortBytes': 52428800},
  41. use_admin=True
  42. ) # 设置排序内存限制
  43. """
  44. if use_admin and command_type == 'dict':
  45. return self['admin'].command(command)
  46. def get_indexes(self, table_name):
  47. """
  48. 获取索引
  49. # return collection.indexes.find()
  50. # return collection.list_indexes()
  51. """
  52. collection = self.db[table_name]
  53. return collection.index_information()
  54. def add_index(self, table_name, index_list):
  55. """
  56. table_name: Xxx
  57. index_list: [("field", 1)]
  58. # return collection.create_index([('sec_id', TEXT)], name='search_index_zyq', default_language='english')
  59. """
  60. collection = self.db[table_name]
  61. return collection.create_index(index_list)
  62. def del_index(self, table_name, index_or_name):
  63. """
  64. 删除索引 https://www.dotnetperls.com/create-index-mongodb
  65. table_name: Xxx
  66. index_list: [("field", 1)]
  67. """
  68. collection = self.db[table_name]
  69. return collection.drop_index(index_or_name)
  70. def add(self, table_name, data):
  71. """
  72. 保存数据
  73. doc: https://www.cnblogs.com/aademeng/articles/9779271.html
  74. """
  75. table = self.db[table_name]
  76. if type(data) == dict:
  77. return str(table.insert_one(data).inserted_id)
  78. elif type(data) == list:
  79. return [str(i) for i in table.insert_many(data).inserted_ids]
  80. def filter(self, table_name, condition_dict, sort_field=None):
  81. """
  82. 筛选数据
  83. condition_dict: 筛选条件
  84. sort_field: [('排序字段', -1)]
  85. """
  86. table = self.db[table_name]
  87. if sort_field:
  88. return table.find(condition_dict).sort(sort_field)
  89. else:
  90. return table.find(condition_dict)
  91. def filter_by_aggregate(self, table_name, condition=None, sort_dict=None, page=None, size=None):
  92. """
  93. 聚合查询
  94. condition: 条件
  95. sort_dict: 排序 {'字段': -1}
  96. page: 页数
  97. size: 条数
  98. """
  99. table = self.db[table_name]
  100. parameters = list()
  101. if condition:
  102. parameters.append({'$match': condition})
  103. if sort_dict:
  104. parameters.append({'$sort': sort_dict})
  105. if type(page) == int and type(size) == int:
  106. skip = 0 if page == 1 else (page - 1) * size
  107. parameters.append({'$skip': skip}) # 跳过多少条
  108. parameters.append({'$limit': size})
  109. return table.aggregate(parameters, allowDiskUse=True)
  110. def get_count(self, table_name, condition_dict=None):
  111. """
  112. 获取数据数量
  113. """
  114. table = self.db[table_name]
  115. if not condition_dict:
  116. condition_dict = {}
  117. return table.count_documents(condition_dict)
  118. def get_all(self, table_name, sort_field=None):
  119. """
  120. 获取数据 / 排序
  121. table_name: '表名'
  122. sort_field: [('排序字段', -1)]
  123. """
  124. table = self.db[table_name]
  125. if sort_field:
  126. return table.find().sort(sort_field)
  127. else:
  128. return table.find()
  129. def get_one(self, table_name, unique_dict):
  130. """
  131. 单条获取
  132. """
  133. table = self.db[table_name]
  134. data = table.find_one(unique_dict)
  135. if data:
  136. return data
  137. else:
  138. return dict()
  139. def get_last_one(self, table_name, sort_list=None):
  140. """
  141. 获取最后一条
  142. table_name: '集合名称'
  143. sort_list: [('_id', -1)]
  144. """
  145. table = self.db[table_name]
  146. if not sort_list:
  147. sort_list = [('_id', -1)]
  148. return table.find_one(sort=sort_list)
  149. def get_one_by_id(self, table_name, object_id):
  150. """
  151. 单条获取
  152. """
  153. table = self.db[table_name]
  154. return table.find_one({'_id': ObjectId(str(object_id))})
  155. def update_one_by_id(self, table_name, object_id, update_dict, need_back=False):
  156. """
  157. 单条数据
  158. """
  159. table = self.db[table_name]
  160. modified_count = table.update_one({'_id': ObjectId(str(object_id))}, {'$set': update_dict}).modified_count
  161. if need_back:
  162. item = self.get_one_by_id(table_name, object_id)
  163. item.pop('_id')
  164. item['uuid'] = object_id
  165. return item
  166. else:
  167. return modified_count
  168. def update_all(self, table_name, condition_dict, update_dict):
  169. """
  170. 批量更新
  171. """
  172. table = self.db[table_name]
  173. return table.update_many(condition_dict, {'$set': update_dict}).matched_count
  174. def update_one(self, table_name, unique_dict, update_dict, default_dict=None, need_back=False):
  175. """
  176. # if get:
  177. # update update_one_by_id
  178. # else:
  179. # insert default_dict
  180. # return: get
  181. """
  182. data = self.get_one(table_name, unique_dict)
  183. if data:
  184. object_id = str(data.get('_id'))
  185. update_dict.update(unique_dict)
  186. self.update_one_by_id(table_name, object_id, update_dict)
  187. else:
  188. if not default_dict:
  189. default_dict = dict()
  190. if '_id' in default_dict:
  191. del default_dict['_id']
  192. default_dict.update(update_dict)
  193. default_dict.update(unique_dict)
  194. object_id = self.add(table_name, default_dict)
  195. if need_back:
  196. return self.get_one_by_id(table_name, object_id)
  197. else:
  198. return object_id
  199. def remove(self, table_name, condition_dict):
  200. """
  201. 批量删除
  202. """
  203. table = self.db[table_name]
  204. return table.delete_many(condition_dict).deleted_count
  205. def remove_one_by_id(self, table_name, object_id):
  206. """
  207. 单条删除
  208. """
  209. table = self.db[table_name]
  210. return table.delete_many({'_id': ObjectId(str(object_id))}).deleted_count
  211. def distinct(self, table_name, field):
  212. """
  213. 去重
  214. """
  215. table = self.db[table_name]
  216. return table.distinct(field)
  217. def get_all_vague(self, table_name, unique_dict):
  218. """
  219. 模糊查询获取
  220. """
  221. table = self.db[table_name]
  222. return table.find(unique_dict)
  223. def get_aggregate(self, table_name, condition):
  224. """
  225. 分组聚合查询(by wdj)
  226. """
  227. table = self.db[table_name]
  228. return table.aggregate(condition)
  229. def get_col_list(self, table_name, condition, _dic):
  230. """
  231. 只返回某一列的数据(by wdj)
  232. """
  233. table = self.db[table_name]
  234. return table.find(condition, _dic)
  235. # def find_by_aggregate(self, table_name,ip):
  236. # """
  237. # 分组查询获取 {"$match":{"ip":ip} {"$group":{"_id":"","counter":{"$sum":1}}}
  238. # """
  239. # table = self.db[table_name]
  240. # count= table.aggregate([{"$group":{"_id":"$find_plugin","count":{"$sum":"$risk_score"}}}])
  241. # return count
  242. def deep_filter(self, collection, field_path, filter_type='equal', filter_value=None, return_count=False,
  243. sort_field=None):
  244. """
  245. field_path: 递进字段名(适用字典类型)
  246. filter_type: 筛选类型 contain !contain equal !equal in !in
  247. sort_field: [('排序字段', -1)]
  248. """
  249. if filter_type == 'equal':
  250. filter_rule = {'$eq': filter_value}
  251. elif filter_type == 'contain':
  252. filter_rule = {'$regex': f'^.*{filter_value}.*$'}
  253. else:
  254. filter_rule = {}
  255. condition = {
  256. field_path: filter_rule
  257. }
  258. if return_count:
  259. return self.get_count(collection, condition)
  260. elif sort_field:
  261. return self.filter(collection, condition, sort_field)
  262. else:
  263. return self.filter(collection, condition)
  264. def del_collect(self):
  265. db_collections = self.db.collection_names()
  266. for collection in db_collections:
  267. self.db[collection].drop()
  268. @staticmethod
  269. def uuid2oid(uuid):
  270. return ObjectId(uuid)
  271. if __name__ == '__main__':
  272. """
  273. sudo python3 -m pip install pymongo
  274. sudo python3 /home/server/projects/taiwuict/cscec-8bur-vms/supplement-python/clients/db_mongo.py
  275. """
  276. # --- init ---
  277. # mdb = Client(database='vms', host='192.168.0.16', port=7030)
  278. # mdb = Client(database='vms', host='192.168.51.242', port=7030)
  279. # mdb = Client(database='vms', host='192.168.1.233', port=7030)
  280. # mdb = Client(database='vms', host='192.168.0.16', port=7030)
  281. # mdb = Client(database='vms', host='10.8.20.115', port=7030) # 晨鸣大厦
  282. # mdb = Client(database='vms', host='192.168.15.195', port=7030)
  283. # mdb = Client(database='vms', host='192.168.0.15', port=7030)
  284. # mdb = Client(database='vms', host='192.168.101.199', port=7030) # 章丘项目
  285. # mdb = Client(database='vms', host='192.168.15.195', port=7030) # 第3现场
  286. # mdb = Client(database='vms', host='192.168.1.242', port=7030) # 第4现场
  287. # mdb = Client(database='ar', host='58.34.94.176', port=7030) # 第4现场
  288. mdb = Client(host='127.0.0.1', port=47017, database='ar', username='admin', password='admin')
  289. # --- test ---
  290. # data = {
  291. # 'username': 'aabbss',
  292. # 'password': 'aabbss',
  293. # 'role_id': 'aabbss',
  294. # 'create_at': 11223344,
  295. # }
  296. # uuid = mdb.add('User', data)
  297. # --- test ---
  298. # __condition = {
  299. # 'face_name': {'$eq': None},
  300. # }
  301. # total = mdb.get_count('Face', __condition)
  302. # print(total)
  303. # total = mdb.remove('Face', __condition)
  304. # print(total)
  305. # total = mdb.get_count('Face', __condition)
  306. # print(total)
  307. # --- test ---
  308. __condition = {
  309. # 'face_name': {'$ne': None},
  310. # 'face_name': {'$eq': None},
  311. 'face_name': {'$regex': '陈忠福'},
  312. # 'face_features': {'$eq': b'\x80\x03N.'},
  313. }
  314. items = mdb.filter('Face', __condition)
  315. # for item in items:
  316. # print(item)
  317. # # print(item.keys())
  318. # total = mdb.get_count('Face', __condition)
  319. # print(total)
  320. # --- test ---
  321. # _id = '62cbbefba007e25f12acea9d'
  322. # out = mdb.get_one_by_id('Face', _id)
  323. # print(out)
  324. # --- test ---
  325. # condition = {
  326. # # 'face_name': {'$eq': None},
  327. # 'face_name': {'$ne': None},
  328. # }
  329. # total = mdb.get_count('Face', condition)
  330. # print(total)
  331. # --- test ---
  332. # items = mdb.get_all('Face')
  333. # for item in items:
  334. # if 'c7304b' in str(item.get('_id')):
  335. # print(item)
  336. # --- test ---
  337. # __condition = {
  338. # # 'face_feature_info_list': {'$ne': None},
  339. # 'face_feature_info_list': {'$eq': None},
  340. # }
  341. # # items = mdb.filter('Face', __condition)
  342. # # for item in items:
  343. # # print(item)
  344. # # break
  345. # total = mdb.get_count('Face', __condition)
  346. # print(total)
  347. # total = mdb.remove('Face', __condition)
  348. # print(total)
  349. # total = mdb.get_count('Face', __condition)
  350. # print(total)
  351. # --- test ---
  352. # unique_dict = {
  353. # 'prc_id': '371324199110201974',
  354. # }
  355. # item = mdb.get_one('Face', unique_dict)
  356. # print(item.get('cscec8_id'))
  357. # --- test ---
  358. # __condition = {
  359. # 'face_type_uuid_list': {'$in': ['62a190ca84b2c038bac3519d', 'aa', '62a1a438024e59b2e654467a']}
  360. # }
  361. # items = mdb.filter('Face', __condition)
  362. # for item in items:
  363. # print(item.get('face_name'))
  364. # --- test ---
  365. # __condition = {
  366. # # 'prc_id': {'$ne': None},
  367. # # 'face_name': {'$ne': None},
  368. # }
  369. # items = mdb.filter('Face', __condition)
  370. # for item in items:
  371. # print(item)
  372. # mdb.update_one_by_id('Face', str(item.get('_id')), {'upload_is': None})
  373. # --- test ---
  374. # total = mdb.get_count('Face', __condition)
  375. # print(total)
  376. # --- test ---
  377. # # _id = '6295942092325efa38758bf1'
  378. # # _id = '629591b792325efa38758be2'
  379. # # _id = '6295925992325efa38758be5'
  380. # _id = '6295915592325efa38758bdf'
  381. # # mdb.update_one_by_id('Face', _id, {'prc_id': '370102198802249999'})
  382. # # mdb.update_one_by_id('Face', _id, {'prc_id': '370102198802241111'})
  383. # mdb.update_one_by_id('Face', _id, {'cscec8_id': 'f6bae517-0a28-429c-b65b-b16548ab2ca4'})
  384. # --- test ---
  385. # import time
  386. #
  387. # __condition = dict(
  388. # modify_at={'$gte': time.time() - 86400 * 100},
  389. # # modify_at={'$gte': methods.now_ts() - 3600},
  390. # )
  391. # items = mdb.filter('Face', __condition)
  392. # for item in items:
  393. # print(item.keys())
  394. # total = mdb.get_count('Face', __condition)
  395. # print(total)
  396. # --- test ---
  397. # __uuid = '6244068e64481ae85ca38ef9'
  398. # item = mdb.get_one_by_id('Face', __uuid)
  399. # print(item)
  400. # --- test ---
  401. # _uuid = '6243fa35d169a1bf065f8f02'
  402. # item = mdb.get_one_by_id('Face', _uuid)
  403. # print(item.get('face_feature_info_list')[0])
  404. # --- test ---
  405. # """
  406. # Face: 陌生人脸表
  407. # Face.face_name: 姓名
  408. # """
  409. # __condition = {
  410. # # 'face_name': {'$ne': None},
  411. # # 'face_name': {'$eq': None},
  412. # 'face_name': {'$regex': '王'},
  413. # }
  414. # items = mdb.filter('Face', __condition)
  415. # for item in items:
  416. # print(item)
  417. # break
  418. # total = mdb.get_count('Face', __condition)
  419. # print(total)
  420. # --- test ---
  421. # __condition = {
  422. # 'name': {'$eq': '未知类型'}
  423. # }
  424. # count = mdb.get_count('FaceType', __condition)
  425. # print(count)
  426. # --- test ---
  427. # items = mdb.get_all('VisitorInfo')
  428. # for item in items:
  429. # _list = item.get('aaabbbccc', [])
  430. # print('_list', type(_list), _list)
  431. # break
  432. # --- test ---
  433. # _condition = {'ipv4': '192.168.30.232'}
  434. # items = mdb.filter_by_aggregate('UserCamera', condition=_condition, sort_dict={'create_at': -1}, page=1,
  435. # size=10)
  436. # count = 0
  437. # for item in items:
  438. # count += 1
  439. # print(count)
  440. # --- test ---
  441. # _uuid = '604c22d22043eb79cb425c9c'
  442. # out = mdb.remove('AgentDetectionRecord', {'camera_uuid': _uuid})
  443. # # out = mdb.get_one('AgentDetectionRecord', {'camera_uuid': _uuid})
  444. # print(out)
  445. # --- test ---
  446. # _condition = {
  447. # '_id': {'$in': [ObjectId('605994eb7c29e9dc3887e639')]}
  448. # }
  449. # items = mdb.filter('AgentDetectionRecord', _condition)
  450. # for item in items:
  451. # print(item)
  452. # --- test ---
  453. # out = mdb.get_count('VisitorInfo')
  454. # print(out)