| 1 |
from abc import ABC |
| 2 |
|
| 3 |
from beanie.odm.operators.find import BaseFindOperator |
| 4 |
|
| 5 |
|
| 6 |
class BaseFindElementOperator(BaseFindOperator, ABC): ... |
| 7 |
|
| 8 |
|
| 9 |
class Exists(BaseFindElementOperator): |
| 10 |
""" |
| 11 |
`$exists` query operator |
| 12 |
|
| 13 |
Example: |
| 14 |
|
| 15 |
```python |
| 16 |
class Product(Document): |
| 17 |
price: float |
| 18 |
|
| 19 |
Exists(Product.price, True) |
| 20 |
``` |
| 21 |
|
| 22 |
Will return query object like |
| 23 |
|
| 24 |
```python |
| 25 |
{"price": {"$exists": True}} |
| 26 |
``` |
| 27 |
|
| 28 |
MongoDB doc: |
| 29 |
<https://docs.mongodb.com/manual/reference/operator/query/exists/> |
| 30 |
""" |
| 31 |
|
| 32 |
def __init__( |
| 33 |
self, |
| 34 |
field, |
| 35 |
value: bool = True, |
| 36 |
): |
| 37 |
self.field = field |
| 38 |
self.value = value |
| 39 |
|
| 40 |
@property |
| 41 |
def query(self): |
| 42 |
return {self.field: {"$exists": self.value}} |
| 43 |
|
| 44 |
|
| 45 |
class Type(BaseFindElementOperator): |
| 46 |
""" |
| 47 |
`$type` query operator |
| 48 |
|
| 49 |
Example: |
| 50 |
|
| 51 |
```python |
| 52 |
class Product(Document): |
| 53 |
price: float |
| 54 |
|
| 55 |
Type(Product.price, "decimal") |
| 56 |
``` |
| 57 |
|
| 58 |
Will return query object like |
| 59 |
|
| 60 |
```python |
| 61 |
{"price": {"$type": "decimal"}} |
| 62 |
``` |
| 63 |
|
| 64 |
MongoDB doc: |
| 65 |
<https://docs.mongodb.com/manual/reference/operator/query/type/> |
| 66 |
""" |
| 67 |
|
| 68 |
def __init__(self, field, types: list[str] | str): |
| 69 |
self.field = field |
| 70 |
self.types = types |
| 71 |
|
| 72 |
@property |
| 73 |
def query(self): |
| 74 |
return {self.field: {"$type": self.types}} |