| 819 | self.assertRaises(InvalidOperation, a.sort, "x", ASCENDING) |
| 820 | |
| 821 | def test_where(self): |
| 822 | db = self.db |
| 823 | db.test.drop() |
| 824 | |
| 825 | a = db.test.find() |
| 826 | with self.assertRaises(TypeError): |
| 827 | a.where(5) # type: ignore[arg-type] |
| 828 | with self.assertRaises(TypeError): |
| 829 | a.where(None) # type: ignore[arg-type] |
| 830 | with self.assertRaises(TypeError): |
| 831 | a.where({}) # type: ignore[arg-type] |
| 832 | |
| 833 | db.test.insert_many([{"x": i} for i in range(10)]) |
| 834 | |
| 835 | self.assertEqual(3, len(db.test.find().where("this.x < 3").to_list())) |
| 836 | self.assertEqual(3, len(db.test.find().where(Code("this.x < 3")).to_list())) |
| 837 | |
| 838 | code_with_scope = Code("this.x < i", {"i": 3}) |
| 839 | if client_context.version.at_least(4, 3, 3): |
| 840 | # MongoDB 4.4 removed support for Code with scope. |
| 841 | with self.assertRaises(OperationFailure): |
| 842 | db.test.find().where(code_with_scope).to_list() |
| 843 | |
| 844 | code_with_empty_scope = Code("this.x < 3", {}) |
| 845 | with self.assertRaises(OperationFailure): |
| 846 | db.test.find().where(code_with_empty_scope).to_list() |
| 847 | else: |
| 848 | self.assertEqual(3, len(db.test.find().where(code_with_scope).to_list())) |
| 849 | |
| 850 | self.assertEqual(10, len(db.test.find().to_list())) |
| 851 | self.assertEqual([0, 1, 2], [a["x"] for a in db.test.find().where("this.x < 3")]) |
| 852 | self.assertEqual([], [a["x"] for a in db.test.find({"x": 5}).where("this.x < 3")]) |
| 853 | self.assertEqual([5], [a["x"] for a in db.test.find({"x": 5}).where("this.x > 3")]) |
| 854 | |
| 855 | cursor = db.test.find().where("this.x < 3").where("this.x > 7") |
| 856 | self.assertEqual([8, 9], [a["x"] for a in cursor]) |
| 857 | |
| 858 | a = db.test.find() |
| 859 | _ = a.where("this.x > 3") |
| 860 | for _ in a: |
| 861 | break |
| 862 | self.assertRaises(InvalidOperation, a.where, "this.x < 3") |
| 863 | |
| 864 | def test_rewind(self): |
| 865 | self.db.test.insert_many([{"x": i} for i in range(1, 4)]) |