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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
|
from abc import abstractmethod
from typing import Any, Dict, List, Optional, Union, cast
from pymongo.asynchronous.client_session import AsyncClientSession
from beanie.odm.fields import ExpressionField
class AggregateMethods:
"""
Aggregate methods
"""
@abstractmethod
def aggregate(
self,
aggregation_pipeline,
projection_model=None,
session: Optional[AsyncClientSession] = None,
ignore_cache: bool = False,
): ...
async def sum(
self,
field: Union[ExpressionField, float, int, str],
session: Optional[AsyncClientSession] = None,
ignore_cache: bool = False,
) -> Optional[float]:
"""
Sum of values of the given field
Example:
```python
class Sample(Document):
price: int
count: int
sum_count = await Document.find(Sample.price <= 100).sum(Sample.count)
```
:param field: Union[ExpressionField, float, int, str]
:param session: Optional[AsyncClientSession] - pymongo session
:param ignore_cache: bool
:return: float - sum. None if there are no items.
"""
pipeline = [
{"$group": {"_id": None, "sum": {"$sum": f"${field}"}}},
{"$project": {"_id": 0, "sum": 1}},
]
# As we did not supply a projection we can safely cast the type (hinting to mypy that we know the type)
result: List[Dict[str, Any]] = cast(
List[Dict[str, Any]],
await self.aggregate(
aggregation_pipeline=pipeline,
session=session,
ignore_cache=ignore_cache,
).to_list(), # type: ignore # TODO: pyright issue, fix
)
if not result:
return None
return result[0]["sum"]
async def avg(
self,
field: Union[ExpressionField, float, int, str],
session: Optional[AsyncClientSession] = None,
ignore_cache: bool = False,
) -> Optional[float]:
"""
Average of values of the given field
Example:
```python
class Sample(Document):
price: int
count: int
avg_count = await Document.find(Sample.price <= 100).avg(Sample.count)
```
:param field: Union[ExpressionField, float, int, str]
:param session: Optional[AsyncClientSession] - pymongo session
:param ignore_cache: bool
:return: Optional[float] - avg. None if there are no items.
"""
pipeline = [
{"$group": {"_id": None, "avg": {"$avg": f"${field}"}}},
{"$project": {"_id": 0, "avg": 1}},
]
result: List[Dict[str, Any]] = cast(
List[Dict[str, Any]],
await self.aggregate(
aggregation_pipeline=pipeline,
session=session,
ignore_cache=ignore_cache,
).to_list(), # type: ignore # TODO: pyright issue, fix
)
if not result:
return None
return result[0]["avg"]
async def max(
self,
field: Union[ExpressionField, str, Any],
session: Optional[AsyncClientSession] = None,
ignore_cache: bool = False,
) -> Optional[Any]:
"""
Max of the values of the given field
Example:
```python
class Sample(Document):
price: int
count: int
max_count = await Document.find(Sample.price <= 100).max(Sample.count)
```
:param field: Union[ExpressionField, str, Any]
:param session: Optional[AsyncClientSession] - pymongo session
:return: Any - max value. None if there are no items.
"""
pipeline = [
{"$group": {"_id": None, "max": {"$max": f"${field}"}}},
{"$project": {"_id": 0, "max": 1}},
]
result: List[Dict[str, Any]] = cast(
List[Dict[str, Any]],
await self.aggregate(
aggregation_pipeline=pipeline,
session=session,
ignore_cache=ignore_cache,
).to_list(), # type: ignore # TODO: pyright issue, fix
)
if not result:
return None
return result[0]["max"]
async def min(
self,
field: Union[ExpressionField, str, Any],
session: Optional[AsyncClientSession] = None,
ignore_cache: bool = False,
) -> Optional[Any]:
"""
Min of the values of the given field
Example:
```python
class Sample(Document):
price: int
count: int
min_count = await Document.find(Sample.price <= 100).min(Sample.count)
```
:param field: Union[ExpressionField, str, Any]
:param session: Optional[AsyncClientSession] - pymongo session
:return: Any - min value. None if there are no items.
"""
pipeline = [
{"$group": {"_id": None, "min": {"$min": f"${field}"}}},
{"$project": {"_id": 0, "min": 1}},
]
result: List[Dict[str, Any]] = cast(
List[Dict[str, Any]],
await self.aggregate(
aggregation_pipeline=pipeline,
session=session,
ignore_cache=ignore_cache,
).to_list(), # type: ignore # TODO: pyright issue, fix
)
if not result:
return None
return result[0]["min"]
|