mongodb.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. @Copyright (C) ansjer cop Video Technology Co.,Ltd.All rights reserved.
  5. @AUTHOR: ASJRD018
  6. @NAME: Ansjer
  7. @software: PyCharm
  8. @DATE: 2018/6/15 14:18
  9. @Version: python3.6
  10. @MODIFY DECORD:ansjer dev
  11. @file: mongodb.py
  12. @Contact: chanjunkai@163.com
  13. """
  14. # !/usr/bin/python3
  15. import pymongo
  16. class mongodb(object):
  17. def __init__(self):
  18. myclient = pymongo.MongoClient('mongodb://localhost:27017/')
  19. # myclient = pymongo.MongoClient('mongodb://192.168.136.45:27017/')
  20. self.myclient = myclient
  21. self.db = myclient['ansjertest']
  22. def check_db_exist(self, database):
  23. dblist = self.myclient.database_names()
  24. if database in dblist:
  25. return True
  26. else:
  27. return False
  28. def insert_one(self, col, data):
  29. column = self.db[col]
  30. res = column.insert_one(data)
  31. return res.inserted_id
  32. def findAll(self, col,page,line,query):
  33. collist = self.db.collection_names()
  34. if col in collist: # 判断 customers 集合是否存在
  35. qs = self.db[col].find(query)
  36. count = qs.count()
  37. if page != 0 and line != 0:
  38. qs = qs.sort("_id", -1).skip((page - 1) * 10).limit(line)
  39. # print(count)
  40. data = []
  41. for q in qs:
  42. data.append(q)
  43. res_dict = {'data': data, 'count': count}
  44. return res_dict
  45. else:
  46. print("集合不存在!")
  47. return False
  48. if __name__ == '__main__':
  49. mdb = mongodb()
  50. col = "log_device_operation"
  51. data = {"name": "111", "address": "Lowstreet 27"}
  52. flag = mdb.insert_one(col=col, data=data)
  53. # qs = mdb.findAll(col=col, page=1, line=100,query={'name':'Peter'})
  54. # print(qs)