-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmongo_client.py
More file actions
70 lines (62 loc) · 2.42 KB
/
mongo_client.py
File metadata and controls
70 lines (62 loc) · 2.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import pymongo
class AdsMongoClient:
def __init__(
self,
host: str,
port: int,
db_name: str = "telegram_bot",
ads_collection_name: str = "ads",
categories_collection_name: str = "categories",
):
self.client = pymongo.MongoClient(host, port)
self.db = self.client.get_database(db_name)
self.ads_collection = self.db.get_collection(ads_collection_name)
self.categories_collection = self.db.get_collection(categories_collection_name)
def add_category(self, category: str):
self.categories_collection.insert_one(
{
"category": category,
}
)
def get_categories(self) -> list:
results = self.categories_collection.find()
return [
result["category"]
for result in results
]
def add_advertising(self, user_id: int, photo_url: str, category: str, description: str):
self.ads_collection.insert_one(
{
"user_id": user_id,
"photo_url": photo_url,
"category": category,
"description": description
}
)
def delete_advertising(self, user_id: int, doc_id: str):
self.ads_collection.delete_one({"_id": doc_id, "user_id": user_id})
def get_ads_by_user_id(self, user_id: int):
results = self.ads_collection.find({"user_id": user_id})
return [
{
"id": str(result["_id"]),
"photo_url": result["photo_url"],
"category": result["category"],
"description": result["description"],
}
for result in results
]
def get_ads_by_category(self, category: str):
# My answer, perform an exact match on the category field and don't care about case sensitivity or partial matches
# results = self.ads_collection.find({"category": category})
# Main answer, perform a case-insensitive search or match categories that contain the search term as a substring
results = self.ads_collection.find({"category": {"$regex": ".*" + category + ".*"}})
return [
{
"id": str(result["_id"]),
"photo_url": result["photo_url"],
"category": result["category"],
"description": result["description"],
}
for result in results
]