db_client.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. from config import load_config
  2. from pymongo import MongoClient
  3. from pymongo.errors import ConnectionFailure
  4. from urllib.parse import quote_plus
  5. import pandas as pd
  6. class MongoClientHelper:
  7. def __init__(self):
  8. self.cfgs = load_config()['mongodb']
  9. self.client = None
  10. self.db = None
  11. if self.client is None:
  12. self.connect()
  13. def connect(self):
  14. """连接MongoDB"""
  15. try:
  16. host = self.cfgs['host']
  17. port = self.cfgs['port']
  18. username = quote_plus(self.cfgs['username'])
  19. password = quote_plus(self.cfgs['password'])
  20. database = self.cfgs['database']
  21. uri = f"mongodb://{username}:{password}@{host}:{port}/{database}?authSource=admin"
  22. self.client = MongoClient(uri)
  23. self.db = self.client[database]
  24. except ConnectionFailure as e:
  25. print(f"MongoDB数据库连接失败: {e}")
  26. def find_one(self, collection_name, query):
  27. """根据条件查询一条结果"""
  28. collection = self.db[collection_name]
  29. return collection.find_one(query)
  30. def find_many(self, collection_name, query):
  31. """根据条件查询多条结果"""
  32. collection = self.db[collection_name]
  33. return collection.find(query)
  34. def find_all(self, collection_name):
  35. """返回mongdb中指定collection中的所有数据"""
  36. collection = self.db[collection_name]
  37. return collection.find()
  38. def find_fields(self, collection_name, fields):
  39. """获取指定字段的所有数据"""
  40. collection = self.db[collection_name]
  41. projection = {field: 1 for field in fields}
  42. projection["_id"] = 0
  43. return collection.find({}, projection)
  44. if __name__ == "__main__":
  45. db_client = MongoClientHelper()
  46. collection_name = 'obrand-ec'
  47. query = {"nick": "李宁篮球旗舰店"}
  48. fields = ["nick"]
  49. res = db_client.find_fields(collection_name, fields)
  50. l = []
  51. for r in res:
  52. l.append(r)
  53. data = pd.DataFrame(l)
  54. print(data)