dao.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. from db import MongoClientHelper
  2. class MongoDao:
  3. _instance = None
  4. def __new__(cls, collection_name):
  5. if not cls._instance:
  6. cls._instance = super(MongoDao, cls).__new__(cls)
  7. cls._instance._initialized = False
  8. return cls._instance
  9. def __init__(self, collection_name):
  10. if not self._initialized:
  11. self.db_client = MongoClientHelper()
  12. self._initialized = True
  13. self.collection_name = collection_name
  14. def get_one_record_by_query(self, query):
  15. res = self.db_client.find_one(self.collection_name, query)
  16. return res
  17. def get_records_by_query(self, query):
  18. collections = self.db_client.find_many(self.collection_name, query)
  19. records = [collection for collection in collections]
  20. return records
  21. def get_one_field_data(self, field):
  22. fields = [field]
  23. """获取指定key的所有数据,返回列表"""
  24. field_records = self.db_client.find_fields(self.collection_name, fields)
  25. return [record[field] for record in field_records]
  26. def get_fields_data(self, fields):
  27. records = self.db_client.find_fields(self.collection_name, fields)
  28. return [record for record in records]
  29. def get_all_records(self):
  30. records = self.db_client.find_all(self.collection_name)
  31. return [record for record in records]
  32. if __name__ == '__main__':
  33. collection_name = "obrand-ec"
  34. dao = MongoDao(collection_name)
  35. field = "nick"
  36. res = dao.get_all_records()
  37. print(len(res))