Adds a `$where`_ clause to this query. The `code` argument must be an instance of :class:`str` or :class:`~bson.code.Code` containing a JavaScript expression. This expression will be evaluated for each document scanned. Only those documents for which the expression e
(self, code: Union[str, Code])
| 804 | return self |
| 805 | |
| 806 | def where(self, code: Union[str, Code]) -> Cursor[_DocumentType]: |
| 807 | """Adds a `$where`_ clause to this query. |
| 808 | |
| 809 | The `code` argument must be an instance of :class:`str` or |
| 810 | :class:`~bson.code.Code` containing a JavaScript expression. |
| 811 | This expression will be evaluated for each document scanned. |
| 812 | Only those documents for which the expression evaluates to |
| 813 | *true* will be returned as results. The keyword *this* refers |
| 814 | to the object currently being scanned. For example:: |
| 815 | |
| 816 | # Find all documents where field "a" is less than "b" plus "c". |
| 817 | for doc in db.test.find().where('this.a < (this.b + this.c)'): |
| 818 | print(doc) |
| 819 | |
| 820 | Raises :class:`TypeError` if `code` is not an instance of |
| 821 | :class:`str`. Raises :class:`~pymongo.errors.InvalidOperation` if this |
| 822 | :class:`Cursor` has already been used. Only the last call to |
| 823 | :meth:`where` applied to a :class:`Cursor` has any effect. |
| 824 | |
| 825 | .. note:: MongoDB 4.4 drops support for :class:`~bson.code.Code` |
| 826 | with scope variables. Consider using `$expr`_ instead. |
| 827 | |
| 828 | :param code: JavaScript expression to use as a filter |
| 829 | |
| 830 | .. _$expr: https://mongodb.com/docs/manual/reference/operator/query/expr/ |
| 831 | .. _$where: https://mongodb.com/docs/manual/reference/operator/query/where/ |
| 832 | """ |
| 833 | self._check_okay_to_chain() |
| 834 | if not isinstance(code, Code): |
| 835 | code = Code(code) |
| 836 | |
| 837 | # Avoid overwriting a filter argument that was given by the user |
| 838 | # when updating the spec. |
| 839 | spec: dict[str, Any] |
| 840 | if self._has_filter: |
| 841 | spec = dict(self._spec) |
| 842 | else: |
| 843 | spec = cast(dict, self._spec) # type: ignore[type-arg] |
| 844 | spec["$where"] = code |
| 845 | self._spec = spec |
| 846 | return self |
| 847 | |
| 848 | def collation(self, collation: Optional[_CollationIn]) -> Cursor[_DocumentType]: |
| 849 | """Adds a :class:`~pymongo.collation.Collation` to this query. |