Debian Codegraph @

beanie/odm/queries/find.py

raw
1 from collections.abc import Callable, Coroutine, Generator, Mapping
2 from typing import (
3 TYPE_CHECKING,
4 Any,
5 Generic,
6 TypeVar,
7 Union,
8 cast,
9 overload,
10 )
11
12 from pydantic import BaseModel
13 from pymongo import ReplaceOne
14 from pymongo.asynchronous.client_session import AsyncClientSession
15 from pymongo.results import UpdateResult
16
17 from beanie.exceptions import DocumentNotFound
18 from beanie.odm.bulk import BulkWriter
19 from beanie.odm.cache import LRUCache
20 from beanie.odm.enums import SortDirection
21 from beanie.odm.interfaces.aggregation_methods import AggregateMethods
22 from beanie.odm.interfaces.clone import CloneInterface
23 from beanie.odm.interfaces.session import SessionMethods
24 from beanie.odm.interfaces.update import UpdateMethods
25 from beanie.odm.operators.find.logical import And
26 from beanie.odm.queries.aggregation import AggregationQuery
27 from beanie.odm.queries.cursor import BaseCursorQuery
28 from beanie.odm.queries.delete import (
29 DeleteMany,
30 DeleteOne,
31 )
32 from beanie.odm.queries.update import (
33 UpdateMany,
34 UpdateOne,
35 UpdateQuery,
36 UpdateResponse,
37 )
38 from beanie.odm.utils.dump import get_dict
39 from beanie.odm.utils.encoder import Encoder
40 from beanie.odm.utils.find import construct_lookup_queries, split_text_query
41 from beanie.odm.utils.parsing import parse_obj
42 from beanie.odm.utils.projection import get_projection
43 from beanie.odm.utils.relations import resolve_query_paths
44
45 if TYPE_CHECKING:
46 from pymongo.asynchronous.command_cursor import AsyncCommandCursor
47 from pymongo.asynchronous.cursor import AsyncCursor
48
49 from beanie.odm.documents import DocType
50
51 FindQueryProjectionType = TypeVar("FindQueryProjectionType", bound=BaseModel)
52 FindQueryResultType = TypeVar("FindQueryResultType", bound=BaseModel)
53
54
55 class FindQuery(
56 Generic[FindQueryResultType], UpdateMethods, SessionMethods, CloneInterface
57 ):
58 """
59 Find Query base class
60 """
61
62 UpdateQueryType: type[UpdateQuery] | type[UpdateMany] | type[UpdateOne] = (
63 UpdateQuery
64 )
65 DeleteQueryType: type[DeleteOne] | type[DeleteMany] = DeleteMany
66 AggregationQueryType = AggregationQuery
67
68 def __init__(self, document_model: type["DocType"]):
69 self.document_model = document_model
70 self.find_expressions: list[Mapping[str, Any]] = []
71 self.projection_model: type[FindQueryResultType] = cast(
72 type[FindQueryResultType], self.document_model
73 )
74 self.session = None
75 self.encoders: dict[Any, Callable[[Any], Any]] = {}
76 self.ignore_cache: bool = False
77 self.encoders = self.document_model.get_bson_encoders()
78 self.fetch_links: bool = False
79 self.pymongo_kwargs: dict[str, Any] = {}
80 self.lazy_parse = False
81 self.nesting_depth: int | None = None
82 self.nesting_depths_per_field: dict[str, int] | None = None
83
84 def prepare_find_expressions(self):
85 if self.document_model.get_link_fields() is not None:
86 for i, query in enumerate(self.find_expressions):
87 self.find_expressions[i] = resolve_query_paths(
88 query,
89 doc=self.document_model, # type: ignore
90 fetch_links=self.fetch_links,
91 )
92
93 def get_filter_query(self) -> dict[str, Any]:
94 """
95
96 Returns: MongoDB filter query
97
98 """
99 self.prepare_find_expressions()
100 if self.find_expressions:
101 return Encoder(custom_encoders=self.encoders).encode(
102 And(*self.find_expressions).query
103 )
104 else:
105 return {}
106
107 def delete(
108 self,
109 session: AsyncClientSession | None = None,
110 bulk_writer: BulkWriter | None = None,
111 **pymongo_kwargs: Any,
112 ) -> DeleteOne | DeleteMany:
113 """
114 Provide search criteria to the Delete query
115
116 :param session: Optional[AsyncClientSession] - pymongo session
117 :return: Union[DeleteOne, DeleteMany]
118 """
119 self.set_session(session=session)
120 return self.DeleteQueryType(
121 document_model=self.document_model,
122 find_query=self.get_filter_query(),
123 bulk_writer=bulk_writer,
124 **pymongo_kwargs,
125 ).set_session(session=session)
126
127 def project(self, projection_model):
128 """
129 Apply projection parameter
130 :param projection_model: Optional[type[BaseModel]] - projection model
131 :return: self
132 """
133 if projection_model is not None:
134 self.projection_model = projection_model
135 return self
136
137 def get_projection_model(self) -> type[FindQueryResultType]:
138 return self.projection_model
139
140 async def count(self) -> int:
141 """
142 Number of found documents
143 :return: int
144 """
145 kwargs = {}
146 if isinstance(self, FindMany):
147 if self.limit_number:
148 kwargs["limit"] = self.limit_number
149 if self.skip_number:
150 kwargs["skip"] = self.skip_number
151 kwargs.update(self.pymongo_kwargs)
152 return (
153 await self.document_model.get_pymongo_collection().count_documents(
154 self.get_filter_query(), session=self.session, **kwargs
155 )
156 )
157
158 async def exists(self) -> bool:
159 """
160 If find query will return anything
161
162 :return: bool
163 """
164 return await self.count() > 0
165
166
167 class FindMany(
168 FindQuery[FindQueryResultType],
169 BaseCursorQuery[FindQueryResultType],
170 AggregateMethods,
171 ):
172 """
173 Find Many query class
174 """
175
176 UpdateQueryType = UpdateMany
177 DeleteQueryType = DeleteMany
178
179 def __init__(self, document_model: type["DocType"]):
180 super().__init__(document_model=document_model)
181 self.sort_expressions: list[tuple[str, SortDirection]] = []
182 self.skip_number: int = 0
183 self.limit_number: int = 0
184
185 @overload
186 def find_many(
187 self: "FindMany[FindQueryResultType]",
188 *args: Mapping[Any, Any] | bool,
189 projection_model: None = None,
190 skip: int | None = None,
191 limit: int | None = None,
192 sort: None | str | list[tuple[str, SortDirection]] = None,
193 session: AsyncClientSession | None = None,
194 ignore_cache: bool = False,
195 fetch_links: bool = False,
196 lazy_parse: bool = False,
197 nesting_depth: int | None = None,
198 nesting_depths_per_field: dict[str, int] | None = None,
199 **pymongo_kwargs: Any,
200 ) -> "FindMany[FindQueryResultType]": ...
201
202 @overload
203 def find_many(
204 self: "FindMany[FindQueryResultType]",
205 *args: Mapping[Any, Any] | bool,
206 projection_model: type[FindQueryProjectionType] | None = None,
207 skip: int | None = None,
208 limit: int | None = None,
209 sort: None | str | list[tuple[str, SortDirection]] = None,
210 session: AsyncClientSession | None = None,
211 ignore_cache: bool = False,
212 fetch_links: bool = False,
213 lazy_parse: bool = False,
214 nesting_depth: int | None = None,
215 nesting_depths_per_field: dict[str, int] | None = None,
216 **pymongo_kwargs: Any,
217 ) -> "FindMany[FindQueryProjectionType]": ...
218
219 def find_many(
220 self: "FindMany[FindQueryResultType]",
221 *args: Mapping[Any, Any] | bool,
222 projection_model: type[FindQueryProjectionType] | None = None,
223 skip: int | None = None,
224 limit: int | None = None,
225 sort: None | str | list[tuple[str, SortDirection]] = None,
226 session: AsyncClientSession | None = None,
227 ignore_cache: bool = False,
228 fetch_links: bool = False,
229 lazy_parse: bool = False,
230 nesting_depth: int | None = None,
231 nesting_depths_per_field: dict[str, int] | None = None,
232 **pymongo_kwargs: Any,
233 ) -> Union[
234 "FindMany[FindQueryResultType]", "FindMany[FindQueryProjectionType]"
235 ]:
236 """
237 Find many documents by criteria
238
239 :param args: *Mapping[Any, Any] - search criteria
240 :param skip: Optional[int] - The number of documents to omit.
241 :param limit: Optional[int] - The maximum number of results to return.
242 :param sort: Union[None, str, list[tuple[str, SortDirection]]] - A key
243 or a list of (key, direction) pairs specifying the sort order
244 for this query.
245 :param projection_model: Optional[type[BaseModel]] - projection model
246 :param session: Optional[AsyncClientSession] - pymongo session
247 :param ignore_cache: bool
248 :param **pymongo_kwargs: pymongo native parameters for find operation (if Document class contains links, this parameter must fit the respective parameter of the aggregate MongoDB function)
249 :return: FindMany - query instance
250 """
251 self.find_expressions += args # type: ignore # bool workaround
252 self.skip(skip)
253 self.limit(limit)
254 self.sort(sort)
255 self.project(projection_model)
256 self.set_session(session=session)
257 self.ignore_cache = ignore_cache
258 self.fetch_links = fetch_links
259 self.pymongo_kwargs.update(pymongo_kwargs)
260 self.nesting_depth = nesting_depth
261 self.nesting_depths_per_field = nesting_depths_per_field
262 if lazy_parse is True:
263 self.lazy_parse = lazy_parse
264 return self
265
266 # TODO probably merge FindOne and FindMany to one class to avoid this
267 # code duplication
268
269 @overload
270 def project(
271 self: "FindMany",
272 projection_model: None,
273 ) -> "FindMany[FindQueryResultType]": ...
274
275 @overload
276 def project(
277 self: "FindMany",
278 projection_model: type[FindQueryProjectionType],
279 ) -> "FindMany[FindQueryProjectionType]": ...
280
281 def project(
282 self: "FindMany",
283 projection_model: type[FindQueryProjectionType] | None,
284 ) -> Union[
285 "FindMany[FindQueryResultType]", "FindMany[FindQueryProjectionType]"
286 ]:
287 """
288 Apply projection parameter
289
290 :param projection_model: Optional[type[BaseModel]] - projection model
291 :return: self
292 """
293 super().project(projection_model)
294 return self
295
296 @overload
297 def find(
298 self: "FindMany[FindQueryResultType]",
299 *args: Mapping[Any, Any] | bool,
300 projection_model: None = None,
301 skip: int | None = None,
302 limit: int | None = None,
303 sort: None | str | list[tuple[str, SortDirection]] = None,
304 session: AsyncClientSession | None = None,
305 ignore_cache: bool = False,
306 fetch_links: bool = False,
307 lazy_parse: bool = False,
308 nesting_depth: int | None = None,
309 nesting_depths_per_field: dict[str, int] | None = None,
310 **pymongo_kwargs: Any,
311 ) -> "FindMany[FindQueryResultType]": ...
312
313 @overload
314 def find(
315 self: "FindMany[FindQueryResultType]",
316 *args: Mapping[Any, Any] | bool,
317 projection_model: type[FindQueryProjectionType] | None = None,
318 skip: int | None = None,
319 limit: int | None = None,
320 sort: None | str | list[tuple[str, SortDirection]] = None,
321 session: AsyncClientSession | None = None,
322 ignore_cache: bool = False,
323 fetch_links: bool = False,
324 lazy_parse: bool = False,
325 nesting_depth: int | None = None,
326 nesting_depths_per_field: dict[str, int] | None = None,
327 **pymongo_kwargs: Any,
328 ) -> "FindMany[FindQueryProjectionType]": ...
329
330 def find(
331 self: "FindMany[FindQueryResultType]",
332 *args: Mapping[Any, Any] | bool,
333 projection_model: type[FindQueryProjectionType] | None = None,
334 skip: int | None = None,
335 limit: int | None = None,
336 sort: None | str | list[tuple[str, SortDirection]] = None,
337 session: AsyncClientSession | None = None,
338 ignore_cache: bool = False,
339 fetch_links: bool = False,
340 lazy_parse: bool = False,
341 nesting_depth: int | None = None,
342 nesting_depths_per_field: dict[str, int] | None = None,
343 **pymongo_kwargs: Any,
344 ) -> Union[
345 "FindMany[FindQueryResultType]", "FindMany[FindQueryProjectionType]"
346 ]:
347 """
348 The same as `find_many(...)`
349 """
350 return self.find_many(
351 *args,
352 skip=skip,
353 limit=limit,
354 sort=sort,
355 projection_model=projection_model,
356 session=session,
357 ignore_cache=ignore_cache,
358 fetch_links=fetch_links or self.fetch_links,
359 lazy_parse=lazy_parse,
360 nesting_depth=nesting_depth,
361 nesting_depths_per_field=nesting_depths_per_field,
362 **pymongo_kwargs,
363 )
364
365 def sort(
366 self,
367 *args: (
368 str
369 | tuple[str, SortDirection]
370 | list[tuple[str, SortDirection]]
371 | None
372 ),
373 ) -> "FindMany[FindQueryResultType]":
374 """
375 Add sort parameters
376 :param args: Union[str, Tuple[str, SortDirection],
377 list[tuple[str, SortDirection]]] - A key or a tuple (key, direction)
378 or a list of (key, direction) pairs specifying
379 the sort order for this query.
380 :return: self
381 """
382 for arg in args:
383 if arg is None:
384 pass
385 elif isinstance(arg, list):
386 self.sort(*arg)
387 elif isinstance(arg, tuple):
388 self.sort_expressions.append(arg)
389 elif isinstance(arg, str):
390 if arg.startswith("+"):
391 self.sort_expressions.append(
392 (arg[1:], SortDirection.ASCENDING)
393 )
394 elif arg.startswith("-"):
395 self.sort_expressions.append(
396 (arg[1:], SortDirection.DESCENDING)
397 )
398 else:
399 self.sort_expressions.append(
400 (arg, SortDirection.ASCENDING)
401 )
402 else:
403 raise TypeError("Wrong argument type")
404 return self
405
406 def skip(self, n: int | None) -> "FindMany[FindQueryResultType]":
407 """
408 Set skip parameter
409 :param n: int
410 :return: self
411 """
412 if n is not None:
413 self.skip_number = n
414 return self
415
416 def limit(self, n: int | None) -> "FindMany[FindQueryResultType]":
417 """
418 Set limit parameter
419 :param n: int
420 :return:
421 """
422 if n is not None:
423 self.limit_number = n
424 return self
425
426 def update(
427 self,
428 *args: Mapping[str, Any],
429 session: AsyncClientSession | None = None,
430 bulk_writer: BulkWriter | None = None,
431 **pymongo_kwargs: Any,
432 ):
433 """
434 Create Update with modifications query
435 and provide search criteria there
436
437 :param args: *Mapping[str,Any] - the modifications to apply.
438 :param session: Optional[AsyncClientSession] - pymongo session
439 :param bulk_writer: Optional[BulkWriter]
440 :return: UpdateMany query
441 """
442 self.set_session(session)
443 return (
444 self.UpdateQueryType(
445 document_model=self.document_model,
446 find_query=self.get_filter_query(),
447 )
448 .update(*args, bulk_writer=bulk_writer, **pymongo_kwargs)
449 .set_session(session=self.session)
450 )
451
452 def upsert(
453 self,
454 *args: Mapping[str, Any],
455 on_insert: "DocType",
456 session: AsyncClientSession | None = None,
457 **pymongo_kwargs: Any,
458 ):
459 """
460 Create Update with modifications query
461 and provide search criteria there
462
463 :param args: *Mapping[str,Any] - the modifications to apply.
464 :param on_insert: DocType - document to insert if there is no matched
465 document in the collection
466 :param session: Optional[AsyncClientSession] - pymongo session
467 :return: UpdateMany query
468 """
469 self.set_session(session)
470 return (
471 self.UpdateQueryType(
472 document_model=self.document_model,
473 find_query=self.get_filter_query(),
474 )
475 .upsert(
476 *args,
477 on_insert=on_insert,
478 **pymongo_kwargs,
479 )
480 .set_session(session=self.session)
481 )
482
483 def update_many(
484 self,
485 *args: Mapping[str, Any],
486 session: AsyncClientSession | None = None,
487 bulk_writer: BulkWriter | None = None,
488 **pymongo_kwargs: Any,
489 ) -> UpdateMany:
490 """
491 Provide search criteria to the
492 [UpdateMany](query.md#updatemany) query
493
494 :param args: *Mapping[str,Any] - the modifications to apply.
495 :param session: Optional[AsyncClientSession] - pymongo session
496 :return: [UpdateMany](query.md#updatemany) query
497 """
498 return cast(
499 UpdateMany,
500 self.update(
501 *args,
502 session=session,
503 bulk_writer=bulk_writer,
504 **pymongo_kwargs,
505 ),
506 )
507
508 def delete_many(
509 self,
510 session: AsyncClientSession | None = None,
511 bulk_writer: BulkWriter | None = None,
512 **pymongo_kwargs: Any,
513 ) -> DeleteMany:
514 """
515 Provide search criteria to the [DeleteMany](query.md#deletemany) query
516
517 :param session: Optional[AsyncClientSession] - pymongo session
518 :return: [DeleteMany](query.md#deletemany) query
519 """
520 # We need to cast here to tell mypy that we are sure about the type.
521 # This is because delete may also return a DeleteOne type in general, and mypy can not be sure in this case
522 # See https://mypy.readthedocs.io/en/stable/common_issues.html#narrowing-and-inner-functions
523 return cast(
524 DeleteMany,
525 self.delete(
526 session=session, bulk_writer=bulk_writer, **pymongo_kwargs
527 ),
528 )
529
530 @overload
531 def aggregate(
532 self,
533 aggregation_pipeline: list[Any],
534 projection_model: None = None,
535 session: AsyncClientSession | None = None,
536 ignore_cache: bool = False,
537 **pymongo_kwargs: Any,
538 ) -> AggregationQuery[dict[str, Any]]: ...
539
540 @overload
541 def aggregate(
542 self,
543 aggregation_pipeline: list[Any],
544 projection_model: type[FindQueryProjectionType],
545 session: AsyncClientSession | None = None,
546 ignore_cache: bool = False,
547 **pymongo_kwargs: Any,
548 ) -> AggregationQuery[FindQueryProjectionType]: ...
549
550 def aggregate(
551 self,
552 aggregation_pipeline: list[dict[str, Any]],
553 projection_model: type[FindQueryProjectionType] | None = None,
554 session: AsyncClientSession | None = None,
555 ignore_cache: bool = False,
556 **pymongo_kwargs: Any,
557 ) -> (
558 AggregationQuery[dict[str, Any]]
559 | AggregationQuery[FindQueryProjectionType]
560 ):
561 """
562 Provide search criteria to the [AggregationQuery](query.md#aggregationquery)
563
564 :param aggregation_pipeline: list - aggregation pipeline. MongoDB doc:
565 <https://docs.mongodb.com/manual/core/aggregation-pipeline/>
566 :param projection_model: type[BaseModel] - Projection Model
567 :param session: Optional[AsyncClientSession] - pymongo session
568 :param ignore_cache: bool
569 :return:[AggregationQuery](query.md#aggregationquery)
570 """
571 self.set_session(session=session)
572 return self.AggregationQueryType(
573 self.document_model,
574 self.build_aggregation_pipeline(*aggregation_pipeline),
575 find_query={},
576 projection_model=projection_model,
577 ignore_cache=ignore_cache,
578 **pymongo_kwargs,
579 ).set_session(session=self.session)
580
581 @property
582 def _cache_key(self) -> str:
583 return LRUCache.create_key(
584 {
585 "type": "FindMany",
586 "filter": self.get_filter_query(),
587 "sort": self.sort_expressions,
588 "projection": get_projection(self.projection_model),
589 "skip": self.skip_number,
590 "limit": self.limit_number,
591 }
592 )
593
594 def _get_cache(self):
595 if (
596 self.document_model.get_settings().use_cache
597 and self.ignore_cache is False
598 ):
599 return self.document_model._cache.get(self._cache_key) # type: ignore
600 else:
601 return None
602
603 def _set_cache(self, data):
604 if (
605 self.document_model.get_settings().use_cache
606 and self.ignore_cache is False
607 ):
608 return self.document_model._cache.set(self._cache_key, data) # type: ignore
609
610 def build_aggregation_pipeline(
611 self, *extra_stages: dict[str, Any]
612 ) -> list[dict[str, Any]]:
613 if self.fetch_links:
614 aggregation_pipeline = construct_lookup_queries(
615 self.document_model,
616 nesting_depth=self.nesting_depth,
617 nesting_depths_per_field=self.nesting_depths_per_field,
618 )
619 else:
620 aggregation_pipeline = []
621 filter_query = self.get_filter_query()
622
623 if filter_query:
624 text_queries, non_text_queries = split_text_query(filter_query)
625
626 if text_queries:
627 aggregation_pipeline.insert(
628 0,
629 {
630 "$match": (
631 {"$and": text_queries}
632 if len(text_queries) > 1
633 else text_queries[0]
634 )
635 },
636 )
637
638 if non_text_queries:
639 aggregation_pipeline.append(
640 {
641 "$match": (
642 {"$and": non_text_queries}
643 if len(non_text_queries) > 1
644 else non_text_queries[0]
645 )
646 }
647 )
648
649 if extra_stages:
650 aggregation_pipeline.extend(extra_stages)
651 sort_pipeline = {"$sort": {i[0]: i[1] for i in self.sort_expressions}}
652 if sort_pipeline["$sort"]:
653 aggregation_pipeline.append(sort_pipeline)
654 if self.skip_number != 0:
655 aggregation_pipeline.append({"$skip": self.skip_number})
656 if self.limit_number != 0:
657 aggregation_pipeline.append({"$limit": self.limit_number})
658 return aggregation_pipeline
659
660 async def get_cursor(
661 self,
662 ) -> "AsyncCommandCursor[dict[str, Any]] | AsyncCursor[dict[str, Any]] | None":
663 if self.fetch_links:
664 aggregation_pipeline = self.build_aggregation_pipeline()
665 projection = get_projection(self.projection_model)
666
667 if projection is not None:
668 aggregation_pipeline.append({"$project": projection})
669
670 return (
671 await self.document_model.get_pymongo_collection().aggregate(
672 aggregation_pipeline,
673 session=self.session,
674 **self.pymongo_kwargs,
675 )
676 )
677
678 return self.document_model.get_pymongo_collection().find(
679 filter=self.get_filter_query(),
680 sort=self.sort_expressions,
681 projection=get_projection(self.projection_model),
682 skip=self.skip_number,
683 limit=self.limit_number,
684 session=self.session,
685 **self.pymongo_kwargs,
686 )
687
688 async def first_or_none(self) -> FindQueryResultType | None:
689 """
690 Returns the first found element or None if no elements were found
691 """
692 existing_limit = self.limit_number
693 try:
694 result = await self.limit(1).to_list()
695 return result[0] if result else None
696 finally:
697 self.limit_number = existing_limit
698
699 async def count(self) -> int:
700 """
701 Number of found documents
702 :return: int
703 """
704 if self.fetch_links:
705 aggregation_pipeline = self.build_aggregation_pipeline()
706 aggregation_pipeline.append({"$count": "count"})
707 cursor = (
708 await self.document_model.get_pymongo_collection().aggregate(
709 aggregation_pipeline,
710 session=self.session,
711 **self.pymongo_kwargs,
712 )
713 )
714 result = await cursor.to_list(length=1)
715
716 return result[0]["count"] if result else 0
717
718 return await super().count()
719
720
721 class FindOne(FindQuery[FindQueryResultType]):
722 """
723 Find One query class
724 """
725
726 UpdateQueryType = UpdateOne
727 DeleteQueryType = DeleteOne
728
729 @overload
730 def project(
731 self: "FindOne[FindQueryResultType]",
732 projection_model: None = None,
733 ) -> "FindOne[FindQueryResultType]": ...
734
735 @overload
736 def project(
737 self: "FindOne[FindQueryResultType]",
738 projection_model: type[FindQueryProjectionType],
739 ) -> "FindOne[FindQueryProjectionType]": ...
740
741 # TODO probably merge FindOne and FindMany to one class to avoid this
742 # code duplication
743
744 def project(
745 self: "FindOne[FindQueryResultType]",
746 projection_model: type[FindQueryProjectionType] | None = None,
747 ) -> Union[
748 "FindOne[FindQueryResultType]", "FindOne[FindQueryProjectionType]"
749 ]:
750 """
751 Apply projection parameter
752 :param projection_model: Optional[type[BaseModel]] - projection model
753 :return: self
754 """
755 super().project(projection_model)
756 return self
757
758 @overload
759 def find_one(
760 self: "FindOne[FindQueryResultType]",
761 *args: Mapping[Any, Any] | bool,
762 projection_model: None = None,
763 session: AsyncClientSession | None = None,
764 ignore_cache: bool = False,
765 fetch_links: bool = False,
766 nesting_depth: int | None = None,
767 nesting_depths_per_field: dict[str, int] | None = None,
768 **pymongo_kwargs: Any,
769 ) -> "FindOne[FindQueryResultType]": ...
770
771 @overload
772 def find_one(
773 self: "FindOne[FindQueryResultType]",
774 *args: Mapping[Any, Any] | bool,
775 projection_model: type[FindQueryProjectionType],
776 session: AsyncClientSession | None = None,
777 ignore_cache: bool = False,
778 fetch_links: bool = False,
779 nesting_depth: int | None = None,
780 nesting_depths_per_field: dict[str, int] | None = None,
781 **pymongo_kwargs: Any,
782 ) -> "FindOne[FindQueryProjectionType]": ...
783
784 def find_one(
785 self: "FindOne[FindQueryResultType]",
786 *args: Mapping[Any, Any] | bool,
787 projection_model: type[FindQueryProjectionType] | None = None,
788 session: AsyncClientSession | None = None,
789 ignore_cache: bool = False,
790 fetch_links: bool = False,
791 nesting_depth: int | None = None,
792 nesting_depths_per_field: dict[str, int] | None = None,
793 **pymongo_kwargs: Any,
794 ) -> Union[
795 "FindOne[FindQueryResultType]", "FindOne[FindQueryProjectionType]"
796 ]:
797 """
798 Find one document by criteria
799
800 :param args: *Mapping[Any, Any] - search criteria
801 :param projection_model: Optional[type[BaseModel]] - projection model
802 :param session: Optional[AsyncClientSession] - pymongo session
803 :param ignore_cache: bool
804 :param **pymongo_kwargs: pymongo native parameters for find operation (if Document class contains links, this parameter must fit the respective parameter of the aggregate MongoDB function)
805 :return: FindOne - query instance
806 """
807 self.find_expressions += args # type: ignore # bool workaround
808 self.project(projection_model)
809 self.set_session(session=session)
810 self.ignore_cache = ignore_cache
811 self.fetch_links = fetch_links or self.fetch_links
812 self.pymongo_kwargs.update(pymongo_kwargs)
813 self.nesting_depth = nesting_depth
814 self.nesting_depths_per_field = nesting_depths_per_field
815 return self
816
817 def update(
818 self,
819 *args: Mapping[str, Any],
820 session: AsyncClientSession | None = None,
821 bulk_writer: BulkWriter | None = None,
822 response_type: UpdateResponse | None = None,
823 **pymongo_kwargs: Any,
824 ):
825 """
826 Create Update with modifications query
827 and provide search criteria there
828
829 :param args: *Mapping[str,Any] - the modifications to apply.
830 :param session: Optional[AsyncClientSession] - pymongo session
831 :param bulk_writer: Optional[BulkWriter]
832 :param response_type: Optional[UpdateResponse]
833 :return: UpdateMany query
834 """
835 self.set_session(session)
836 return (
837 self.UpdateQueryType(
838 document_model=self.document_model,
839 find_query=self.get_filter_query(),
840 )
841 .update(
842 *args,
843 bulk_writer=bulk_writer,
844 response_type=response_type,
845 **pymongo_kwargs,
846 )
847 .set_session(session=self.session)
848 )
849
850 def upsert(
851 self,
852 *args: Mapping[str, Any],
853 on_insert: "DocType",
854 session: AsyncClientSession | None = None,
855 response_type: UpdateResponse | None = None,
856 **pymongo_kwargs: Any,
857 ):
858 """
859 Create Update with modifications query
860 and provide search criteria there
861
862 :param args: *Mapping[str,Any] - the modifications to apply.
863 :param on_insert: DocType - document to insert if there is no matched
864 document in the collection
865 :param session: Optional[AsyncClientSession] - pymongo session
866 :param response_type: Optional[UpdateResponse]
867 :return: UpdateMany query
868 """
869 self.set_session(session)
870 return (
871 self.UpdateQueryType(
872 document_model=self.document_model,
873 find_query=self.get_filter_query(),
874 )
875 .upsert(
876 *args,
877 on_insert=on_insert,
878 response_type=response_type,
879 **pymongo_kwargs,
880 )
881 .set_session(session=self.session)
882 )
883
884 def update_one(
885 self,
886 *args: Mapping[str, Any],
887 session: AsyncClientSession | None = None,
888 bulk_writer: BulkWriter | None = None,
889 response_type: UpdateResponse | None = None,
890 **pymongo_kwargs: Any,
891 ) -> UpdateOne:
892 """
893 Create [UpdateOne](query.md#updateone) query using modifications and
894 provide search criteria there
895 :param args: *Mapping[str,Any] - the modifications to apply
896 :param session: Optional[AsyncClientSession] - pymongo session
897 :param response_type: Optional[UpdateResponse]
898 :return: [UpdateOne](query.md#updateone) query
899 """
900 return cast(
901 UpdateOne,
902 self.update(
903 *args,
904 session=session,
905 bulk_writer=bulk_writer,
906 response_type=response_type,
907 **pymongo_kwargs,
908 ),
909 )
910
911 def delete_one(
912 self,
913 session: AsyncClientSession | None = None,
914 bulk_writer: BulkWriter | None = None,
915 **pymongo_kwargs: Any,
916 ) -> DeleteOne:
917 """
918 Provide search criteria to the [DeleteOne](query.md#deleteone) query
919 :param session: Optional[AsyncClientSession] - pymongo session
920 :return: [DeleteOne](query.md#deleteone) query
921 """
922 # We need to cast here to tell mypy that we are sure about the type.
923 # This is because delete may also return a DeleteOne type in general, and mypy can not be sure in this case
924 # See https://mypy.readthedocs.io/en/stable/common_issues.html#narrowing-and-inner-functions
925 return cast(
926 DeleteOne,
927 self.delete(
928 session=session, bulk_writer=bulk_writer, **pymongo_kwargs
929 ),
930 )
931
932 async def replace_one(
933 self,
934 document: "DocType",
935 session: AsyncClientSession | None = None,
936 bulk_writer: BulkWriter | None = None,
937 ) -> UpdateResult | None:
938 """
939 Replace found document by provided
940 :param document: Document - document, which will replace the found one
941 :param session: Optional[AsyncClientSession] - pymongo session
942 :param bulk_writer: Optional[BulkWriter] - Beanie bulk writer
943 :return: UpdateResult
944 """
945 self.set_session(session=session)
946 if bulk_writer is None:
947 result: UpdateResult = (
948 await self.document_model.get_pymongo_collection().replace_one(
949 self.get_filter_query(),
950 get_dict(
951 document,
952 to_db=True,
953 exclude={"_id"},
954 keep_nulls=document.get_settings().keep_nulls,
955 ),
956 session=self.session,
957 )
958 )
959
960 if not result.raw_result["updatedExisting"]:
961 raise DocumentNotFound
962 return result
963 else:
964 bulk_writer.add_operation(
965 self.document_model,
966 ReplaceOne(
967 self.get_filter_query(),
968 get_dict(
969 document,
970 to_db=True,
971 exclude={"_id"},
972 keep_nulls=document.get_settings().keep_nulls,
973 ),
974 **self.pymongo_kwargs,
975 ),
976 )
977 return None
978
979 async def _find_one(self):
980 if self.fetch_links:
981 return await self.document_model.find_many(
982 *self.find_expressions,
983 session=self.session,
984 fetch_links=self.fetch_links,
985 projection_model=self.projection_model,
986 nesting_depth=self.nesting_depth,
987 nesting_depths_per_field=self.nesting_depths_per_field,
988 **self.pymongo_kwargs,
989 ).first_or_none()
990 return await self.document_model.get_pymongo_collection().find_one(
991 filter=self.get_filter_query(),
992 projection=get_projection(self.projection_model),
993 session=self.session,
994 **self.pymongo_kwargs,
995 )
996
997 def __await__(
998 self,
999 ) -> Generator[Coroutine, Any, FindQueryResultType | None]:
1000 """
1001 Run the query
1002 :return: BaseModel
1003 """
1004 # projection = get_projection(self.projection_model)
1005 if (
1006 self.document_model.get_settings().use_cache
1007 and self.ignore_cache is False
1008 ):
1009 cache_key = LRUCache.create_key(
1010 "FindOne",
1011 self.get_filter_query(),
1012 self.projection_model,
1013 self.session,
1014 self.fetch_links,
1015 )
1016 document: dict[str, Any] = self.document_model._cache.get( # type: ignore
1017 cache_key
1018 )
1019 if document is None:
1020 document = yield from self._find_one().__await__() # type: ignore
1021 self.document_model._cache.set(cache_key, document) # type: ignore
1022 else:
1023 document = yield from self._find_one().__await__() # type: ignore
1024 if document is None:
1025 return None
1026 if type(document) is self.projection_model:
1027 return cast(FindQueryResultType, document)
1028 return cast(
1029 FindQueryResultType, parse_obj(self.projection_model, document)
1030 )
1031
1032 async def count(self) -> int:
1033 """
1034 Count the number of documents matching the query
1035 :return: int
1036 """
1037 if self.fetch_links:
1038 return await self.document_model.find_many(
1039 *self.find_expressions,
1040 session=self.session,
1041 fetch_links=self.fetch_links,
1042 **self.pymongo_kwargs,
1043 ).count()
1044 return await super().count()