We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add alias argument in query_counter
The context_managers.query_counter constructor currently does not accept any arguments.

In my case, I define custom aliases and do not use the default one. When instantiating a query_counter, it calls get_db with no arguments which means that it tries to get the default alias, and throws the following exception:
`mongoengine.connection.MongoEngineConnectionError: You have not defined a default connection`

This problem is easily solved by adding an "alias" parameter in the constructor for query_counter. I can push a PR if you are interested.

Thanks !

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `mongoengine/context_managers.py`
Content:
```
1 from contextlib import contextmanager
2 
3 from pymongo.write_concern import WriteConcern
4 from six import iteritems
5 
6 from mongoengine.common import _import_class
7 from mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db
8 from mongoengine.pymongo_support import count_documents
9 
10 __all__ = (
11     "switch_db",
12     "switch_collection",
13     "no_dereference",
14     "no_sub_classes",
15     "query_counter",
16     "set_write_concern",
17 )
18 
19 
20 class switch_db(object):
21     """switch_db alias context manager.
22 
23     Example ::
24 
25         # Register connections
26         register_connection('default', 'mongoenginetest')
27         register_connection('testdb-1', 'mongoenginetest2')
28 
29         class Group(Document):
30             name = StringField()
31 
32         Group(name='test').save()  # Saves in the default db
33 
34         with switch_db(Group, 'testdb-1') as Group:
35             Group(name='hello testdb!').save()  # Saves in testdb-1
36     """
37 
38     def __init__(self, cls, db_alias):
39         """Construct the switch_db context manager
40 
41         :param cls: the class to change the registered db
42         :param db_alias: the name of the specific database to use
43         """
44         self.cls = cls
45         self.collection = cls._get_collection()
46         self.db_alias = db_alias
47         self.ori_db_alias = cls._meta.get("db_alias", DEFAULT_CONNECTION_NAME)
48 
49     def __enter__(self):
50         """Change the db_alias and clear the cached collection."""
51         self.cls._meta["db_alias"] = self.db_alias
52         self.cls._collection = None
53         return self.cls
54 
55     def __exit__(self, t, value, traceback):
56         """Reset the db_alias and collection."""
57         self.cls._meta["db_alias"] = self.ori_db_alias
58         self.cls._collection = self.collection
59 
60 
61 class switch_collection(object):
62     """switch_collection alias context manager.
63 
64     Example ::
65 
66         class Group(Document):
67             name = StringField()
68 
69         Group(name='test').save()  # Saves in the default db
70 
71         with switch_collection(Group, 'group1') as Group:
72             Group(name='hello testdb!').save()  # Saves in group1 collection
73     """
74 
75     def __init__(self, cls, collection_name):
76         """Construct the switch_collection context manager.
77 
78         :param cls: the class to change the registered db
79         :param collection_name: the name of the collection to use
80         """
81         self.cls = cls
82         self.ori_collection = cls._get_collection()
83         self.ori_get_collection_name = cls._get_collection_name
84         self.collection_name = collection_name
85 
86     def __enter__(self):
87         """Change the _get_collection_name and clear the cached collection."""
88 
89         @classmethod
90         def _get_collection_name(cls):
91             return self.collection_name
92 
93         self.cls._get_collection_name = _get_collection_name
94         self.cls._collection = None
95         return self.cls
96 
97     def __exit__(self, t, value, traceback):
98         """Reset the collection."""
99         self.cls._collection = self.ori_collection
100         self.cls._get_collection_name = self.ori_get_collection_name
101 
102 
103 class no_dereference(object):
104     """no_dereference context manager.
105 
106     Turns off all dereferencing in Documents for the duration of the context
107     manager::
108 
109         with no_dereference(Group) as Group:
110             Group.objects.find()
111     """
112 
113     def __init__(self, cls):
114         """Construct the no_dereference context manager.
115 
116         :param cls: the class to turn dereferencing off on
117         """
118         self.cls = cls
119 
120         ReferenceField = _import_class("ReferenceField")
121         GenericReferenceField = _import_class("GenericReferenceField")
122         ComplexBaseField = _import_class("ComplexBaseField")
123 
124         self.deref_fields = [
125             k
126             for k, v in iteritems(self.cls._fields)
127             if isinstance(v, (ReferenceField, GenericReferenceField, ComplexBaseField))
128         ]
129 
130     def __enter__(self):
131         """Change the objects default and _auto_dereference values."""
132         for field in self.deref_fields:
133             self.cls._fields[field]._auto_dereference = False
134         return self.cls
135 
136     def __exit__(self, t, value, traceback):
137         """Reset the default and _auto_dereference values."""
138         for field in self.deref_fields:
139             self.cls._fields[field]._auto_dereference = True
140         return self.cls
141 
142 
143 class no_sub_classes(object):
144     """no_sub_classes context manager.
145 
146     Only returns instances of this class and no sub (inherited) classes::
147 
148         with no_sub_classes(Group) as Group:
149             Group.objects.find()
150     """
151 
152     def __init__(self, cls):
153         """Construct the no_sub_classes context manager.
154 
155         :param cls: the class to turn querying sub classes on
156         """
157         self.cls = cls
158         self.cls_initial_subclasses = None
159 
160     def __enter__(self):
161         """Change the objects default and _auto_dereference values."""
162         self.cls_initial_subclasses = self.cls._subclasses
163         self.cls._subclasses = (self.cls._class_name,)
164         return self.cls
165 
166     def __exit__(self, t, value, traceback):
167         """Reset the default and _auto_dereference values."""
168         self.cls._subclasses = self.cls_initial_subclasses
169 
170 
171 class query_counter(object):
172     """Query_counter context manager to get the number of queries.
173     This works by updating the `profiling_level` of the database so that all queries get logged,
174     resetting the db.system.profile collection at the beginnig of the context and counting the new entries.
175 
176     This was designed for debugging purpose. In fact it is a global counter so queries issued by other threads/processes
177     can interfere with it
178 
179     Be aware that:
180     - Iterating over large amount of documents (>101) makes pymongo issue `getmore` queries to fetch the next batch of
181         documents (https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/#cursor-batches)
182     - Some queries are ignored by default by the counter (killcursors, db.system.indexes)
183     """
184 
185     def __init__(self):
186         """Construct the query_counter
187         """
188         self.db = get_db()
189         self.initial_profiling_level = None
190         self._ctx_query_counter = 0  # number of queries issued by the context
191 
192         self._ignored_query = {
193             "ns": {"$ne": "%s.system.indexes" % self.db.name},
194             "op": {"$ne": "killcursors"},  # MONGODB < 3.2
195             "command.killCursors": {"$exists": False},  # MONGODB >= 3.2
196         }
197 
198     def _turn_on_profiling(self):
199         self.initial_profiling_level = self.db.profiling_level()
200         self.db.set_profiling_level(0)
201         self.db.system.profile.drop()
202         self.db.set_profiling_level(2)
203 
204     def _resets_profiling(self):
205         self.db.set_profiling_level(self.initial_profiling_level)
206 
207     def __enter__(self):
208         self._turn_on_profiling()
209         return self
210 
211     def __exit__(self, t, value, traceback):
212         self._resets_profiling()
213 
214     def __eq__(self, value):
215         counter = self._get_count()
216         return value == counter
217 
218     def __ne__(self, value):
219         return not self.__eq__(value)
220 
221     def __lt__(self, value):
222         return self._get_count() < value
223 
224     def __le__(self, value):
225         return self._get_count() <= value
226 
227     def __gt__(self, value):
228         return self._get_count() > value
229 
230     def __ge__(self, value):
231         return self._get_count() >= value
232 
233     def __int__(self):
234         return self._get_count()
235 
236     def __repr__(self):
237         """repr query_counter as the number of queries."""
238         return u"%s" % self._get_count()
239 
240     def _get_count(self):
241         """Get the number of queries by counting the current number of entries in db.system.profile
242         and substracting the queries issued by this context. In fact everytime this is called, 1 query is
243         issued so we need to balance that
244         """
245         count = (
246             count_documents(self.db.system.profile, self._ignored_query)
247             - self._ctx_query_counter
248         )
249         self._ctx_query_counter += (
250             1  # Account for the query we just issued to gather the information
251         )
252         return count
253 
254 
255 @contextmanager
256 def set_write_concern(collection, write_concerns):
257     combined_concerns = dict(collection.write_concern.document.items())
258     combined_concerns.update(write_concerns)
259     yield collection.with_options(write_concern=WriteConcern(**combined_concerns))
260
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/mongoengine/context_managers.py b/mongoengine/context_managers.py
--- a/mongoengine/context_managers.py
+++ b/mongoengine/context_managers.py
@@ -182,10 +182,10 @@
     - Some queries are ignored by default by the counter (killcursors, db.system.indexes)
     """
 
-    def __init__(self):
+    def __init__(self, alias=DEFAULT_CONNECTION_NAME):
         """Construct the query_counter
         """
-        self.db = get_db()
+        self.db = get_db(alias=alias)
         self.initial_profiling_level = None
         self._ctx_query_counter = 0  # number of queries issued by the context

{"golden_diff": "diff --git a/mongoengine/context_managers.py b/mongoengine/context_managers.py\n--- a/mongoengine/context_managers.py\n+++ b/mongoengine/context_managers.py\n@@ -182,10 +182,10 @@\n     - Some queries are ignored by default by the counter (killcursors, db.system.indexes)\n     \"\"\"\n \n-    def __init__(self):\n+    def __init__(self, alias=DEFAULT_CONNECTION_NAME):\n         \"\"\"Construct the query_counter\n         \"\"\"\n-        self.db = get_db()\n+        self.db = get_db(alias=alias)\n         self.initial_profiling_level = None\n         self._ctx_query_counter = 0  # number of queries issued by the context\n", "issue": "Add alias argument in query_counter\nThe context_managers.query_counter constructor currently does not accept any arguments.\r\n\r\nIn my case, I define custom aliases and do not use the default one. When instantiating a query_counter, it calls get_db with no arguments which means that it tries to get the default alias, and throws the following exception:\r\n`mongoengine.connection.MongoEngineConnectionError: You have not defined a default connection`\r\n\r\nThis problem is easily solved by adding an \"alias\" parameter in the constructor for query_counter. I can push a PR if you are interested.\r\n\r\nThanks !\n", "before_files": [{"content": "from contextlib import contextmanager\n\nfrom pymongo.write_concern import WriteConcern\nfrom six import iteritems\n\nfrom mongoengine.common import _import_class\nfrom mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db\nfrom mongoengine.pymongo_support import count_documents\n\n__all__ = (\n    \"switch_db\",\n    \"switch_collection\",\n    \"no_dereference\",\n    \"no_sub_classes\",\n    \"query_counter\",\n    \"set_write_concern\",\n)\n\n\nclass switch_db(object):\n    \"\"\"switch_db alias context manager.\n\n    Example ::\n\n        # Register connections\n        register_connection('default', 'mongoenginetest')\n        register_connection('testdb-1', 'mongoenginetest2')\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_db(Group, 'testdb-1') as Group:\n            Group(name='hello testdb!').save()  # Saves in testdb-1\n    \"\"\"\n\n    def __init__(self, cls, db_alias):\n        \"\"\"Construct the switch_db context manager\n\n        :param cls: the class to change the registered db\n        :param db_alias: the name of the specific database to use\n        \"\"\"\n        self.cls = cls\n        self.collection = cls._get_collection()\n        self.db_alias = db_alias\n        self.ori_db_alias = cls._meta.get(\"db_alias\", DEFAULT_CONNECTION_NAME)\n\n    def __enter__(self):\n        \"\"\"Change the db_alias and clear the cached collection.\"\"\"\n        self.cls._meta[\"db_alias\"] = self.db_alias\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the db_alias and collection.\"\"\"\n        self.cls._meta[\"db_alias\"] = self.ori_db_alias\n        self.cls._collection = self.collection\n\n\nclass switch_collection(object):\n    \"\"\"switch_collection alias context manager.\n\n    Example ::\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_collection(Group, 'group1') as Group:\n            Group(name='hello testdb!').save()  # Saves in group1 collection\n    \"\"\"\n\n    def __init__(self, cls, collection_name):\n        \"\"\"Construct the switch_collection context manager.\n\n        :param cls: the class to change the registered db\n        :param collection_name: the name of the collection to use\n        \"\"\"\n        self.cls = cls\n        self.ori_collection = cls._get_collection()\n        self.ori_get_collection_name = cls._get_collection_name\n        self.collection_name = collection_name\n\n    def __enter__(self):\n        \"\"\"Change the _get_collection_name and clear the cached collection.\"\"\"\n\n        @classmethod\n        def _get_collection_name(cls):\n            return self.collection_name\n\n        self.cls._get_collection_name = _get_collection_name\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the collection.\"\"\"\n        self.cls._collection = self.ori_collection\n        self.cls._get_collection_name = self.ori_get_collection_name\n\n\nclass no_dereference(object):\n    \"\"\"no_dereference context manager.\n\n    Turns off all dereferencing in Documents for the duration of the context\n    manager::\n\n        with no_dereference(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_dereference context manager.\n\n        :param cls: the class to turn dereferencing off on\n        \"\"\"\n        self.cls = cls\n\n        ReferenceField = _import_class(\"ReferenceField\")\n        GenericReferenceField = _import_class(\"GenericReferenceField\")\n        ComplexBaseField = _import_class(\"ComplexBaseField\")\n\n        self.deref_fields = [\n            k\n            for k, v in iteritems(self.cls._fields)\n            if isinstance(v, (ReferenceField, GenericReferenceField, ComplexBaseField))\n        ]\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = False\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = True\n        return self.cls\n\n\nclass no_sub_classes(object):\n    \"\"\"no_sub_classes context manager.\n\n    Only returns instances of this class and no sub (inherited) classes::\n\n        with no_sub_classes(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_sub_classes context manager.\n\n        :param cls: the class to turn querying sub classes on\n        \"\"\"\n        self.cls = cls\n        self.cls_initial_subclasses = None\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        self.cls_initial_subclasses = self.cls._subclasses\n        self.cls._subclasses = (self.cls._class_name,)\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        self.cls._subclasses = self.cls_initial_subclasses\n\n\nclass query_counter(object):\n    \"\"\"Query_counter context manager to get the number of queries.\n    This works by updating the `profiling_level` of the database so that all queries get logged,\n    resetting the db.system.profile collection at the beginnig of the context and counting the new entries.\n\n    This was designed for debugging purpose. In fact it is a global counter so queries issued by other threads/processes\n    can interfere with it\n\n    Be aware that:\n    - Iterating over large amount of documents (>101) makes pymongo issue `getmore` queries to fetch the next batch of\n        documents (https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/#cursor-batches)\n    - Some queries are ignored by default by the counter (killcursors, db.system.indexes)\n    \"\"\"\n\n    def __init__(self):\n        \"\"\"Construct the query_counter\n        \"\"\"\n        self.db = get_db()\n        self.initial_profiling_level = None\n        self._ctx_query_counter = 0  # number of queries issued by the context\n\n        self._ignored_query = {\n            \"ns\": {\"$ne\": \"%s.system.indexes\" % self.db.name},\n            \"op\": {\"$ne\": \"killcursors\"},  # MONGODB < 3.2\n            \"command.killCursors\": {\"$exists\": False},  # MONGODB >= 3.2\n        }\n\n    def _turn_on_profiling(self):\n        self.initial_profiling_level = self.db.profiling_level()\n        self.db.set_profiling_level(0)\n        self.db.system.profile.drop()\n        self.db.set_profiling_level(2)\n\n    def _resets_profiling(self):\n        self.db.set_profiling_level(self.initial_profiling_level)\n\n    def __enter__(self):\n        self._turn_on_profiling()\n        return self\n\n    def __exit__(self, t, value, traceback):\n        self._resets_profiling()\n\n    def __eq__(self, value):\n        counter = self._get_count()\n        return value == counter\n\n    def __ne__(self, value):\n        return not self.__eq__(value)\n\n    def __lt__(self, value):\n        return self._get_count() < value\n\n    def __le__(self, value):\n        return self._get_count() <= value\n\n    def __gt__(self, value):\n        return self._get_count() > value\n\n    def __ge__(self, value):\n        return self._get_count() >= value\n\n    def __int__(self):\n        return self._get_count()\n\n    def __repr__(self):\n        \"\"\"repr query_counter as the number of queries.\"\"\"\n        return u\"%s\" % self._get_count()\n\n    def _get_count(self):\n        \"\"\"Get the number of queries by counting the current number of entries in db.system.profile\n        and substracting the queries issued by this context. In fact everytime this is called, 1 query is\n        issued so we need to balance that\n        \"\"\"\n        count = (\n            count_documents(self.db.system.profile, self._ignored_query)\n            - self._ctx_query_counter\n        )\n        self._ctx_query_counter += (\n            1  # Account for the query we just issued to gather the information\n        )\n        return count\n\n\n@contextmanager\ndef set_write_concern(collection, write_concerns):\n    combined_concerns = dict(collection.write_concern.document.items())\n    combined_concerns.update(write_concerns)\n    yield collection.with_options(write_concern=WriteConcern(**combined_concerns))\n", "path": "mongoengine/context_managers.py"}], "after_files": [{"content": "from contextlib import contextmanager\n\nfrom pymongo.write_concern import WriteConcern\nfrom six import iteritems\n\nfrom mongoengine.common import _import_class\nfrom mongoengine.connection import DEFAULT_CONNECTION_NAME, get_db\nfrom mongoengine.pymongo_support import count_documents\n\n__all__ = (\n    \"switch_db\",\n    \"switch_collection\",\n    \"no_dereference\",\n    \"no_sub_classes\",\n    \"query_counter\",\n    \"set_write_concern\",\n)\n\n\nclass switch_db(object):\n    \"\"\"switch_db alias context manager.\n\n    Example ::\n\n        # Register connections\n        register_connection('default', 'mongoenginetest')\n        register_connection('testdb-1', 'mongoenginetest2')\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_db(Group, 'testdb-1') as Group:\n            Group(name='hello testdb!').save()  # Saves in testdb-1\n    \"\"\"\n\n    def __init__(self, cls, db_alias):\n        \"\"\"Construct the switch_db context manager\n\n        :param cls: the class to change the registered db\n        :param db_alias: the name of the specific database to use\n        \"\"\"\n        self.cls = cls\n        self.collection = cls._get_collection()\n        self.db_alias = db_alias\n        self.ori_db_alias = cls._meta.get(\"db_alias\", DEFAULT_CONNECTION_NAME)\n\n    def __enter__(self):\n        \"\"\"Change the db_alias and clear the cached collection.\"\"\"\n        self.cls._meta[\"db_alias\"] = self.db_alias\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the db_alias and collection.\"\"\"\n        self.cls._meta[\"db_alias\"] = self.ori_db_alias\n        self.cls._collection = self.collection\n\n\nclass switch_collection(object):\n    \"\"\"switch_collection alias context manager.\n\n    Example ::\n\n        class Group(Document):\n            name = StringField()\n\n        Group(name='test').save()  # Saves in the default db\n\n        with switch_collection(Group, 'group1') as Group:\n            Group(name='hello testdb!').save()  # Saves in group1 collection\n    \"\"\"\n\n    def __init__(self, cls, collection_name):\n        \"\"\"Construct the switch_collection context manager.\n\n        :param cls: the class to change the registered db\n        :param collection_name: the name of the collection to use\n        \"\"\"\n        self.cls = cls\n        self.ori_collection = cls._get_collection()\n        self.ori_get_collection_name = cls._get_collection_name\n        self.collection_name = collection_name\n\n    def __enter__(self):\n        \"\"\"Change the _get_collection_name and clear the cached collection.\"\"\"\n\n        @classmethod\n        def _get_collection_name(cls):\n            return self.collection_name\n\n        self.cls._get_collection_name = _get_collection_name\n        self.cls._collection = None\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the collection.\"\"\"\n        self.cls._collection = self.ori_collection\n        self.cls._get_collection_name = self.ori_get_collection_name\n\n\nclass no_dereference(object):\n    \"\"\"no_dereference context manager.\n\n    Turns off all dereferencing in Documents for the duration of the context\n    manager::\n\n        with no_dereference(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_dereference context manager.\n\n        :param cls: the class to turn dereferencing off on\n        \"\"\"\n        self.cls = cls\n\n        ReferenceField = _import_class(\"ReferenceField\")\n        GenericReferenceField = _import_class(\"GenericReferenceField\")\n        ComplexBaseField = _import_class(\"ComplexBaseField\")\n\n        self.deref_fields = [\n            k\n            for k, v in iteritems(self.cls._fields)\n            if isinstance(v, (ReferenceField, GenericReferenceField, ComplexBaseField))\n        ]\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = False\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        for field in self.deref_fields:\n            self.cls._fields[field]._auto_dereference = True\n        return self.cls\n\n\nclass no_sub_classes(object):\n    \"\"\"no_sub_classes context manager.\n\n    Only returns instances of this class and no sub (inherited) classes::\n\n        with no_sub_classes(Group) as Group:\n            Group.objects.find()\n    \"\"\"\n\n    def __init__(self, cls):\n        \"\"\"Construct the no_sub_classes context manager.\n\n        :param cls: the class to turn querying sub classes on\n        \"\"\"\n        self.cls = cls\n        self.cls_initial_subclasses = None\n\n    def __enter__(self):\n        \"\"\"Change the objects default and _auto_dereference values.\"\"\"\n        self.cls_initial_subclasses = self.cls._subclasses\n        self.cls._subclasses = (self.cls._class_name,)\n        return self.cls\n\n    def __exit__(self, t, value, traceback):\n        \"\"\"Reset the default and _auto_dereference values.\"\"\"\n        self.cls._subclasses = self.cls_initial_subclasses\n\n\nclass query_counter(object):\n    \"\"\"Query_counter context manager to get the number of queries.\n    This works by updating the `profiling_level` of the database so that all queries get logged,\n    resetting the db.system.profile collection at the beginnig of the context and counting the new entries.\n\n    This was designed for debugging purpose. In fact it is a global counter so queries issued by other threads/processes\n    can interfere with it\n\n    Be aware that:\n    - Iterating over large amount of documents (>101) makes pymongo issue `getmore` queries to fetch the next batch of\n        documents (https://docs.mongodb.com/manual/tutorial/iterate-a-cursor/#cursor-batches)\n    - Some queries are ignored by default by the counter (killcursors, db.system.indexes)\n    \"\"\"\n\n    def __init__(self, alias=DEFAULT_CONNECTION_NAME):\n        \"\"\"Construct the query_counter\n        \"\"\"\n        self.db = get_db(alias=alias)\n        self.initial_profiling_level = None\n        self._ctx_query_counter = 0  # number of queries issued by the context\n\n        self._ignored_query = {\n            \"ns\": {\"$ne\": \"%s.system.indexes\" % self.db.name},\n            \"op\": {\"$ne\": \"killcursors\"},  # MONGODB < 3.2\n            \"command.killCursors\": {\"$exists\": False},  # MONGODB >= 3.2\n        }\n\n    def _turn_on_profiling(self):\n        self.initial_profiling_level = self.db.profiling_level()\n        self.db.set_profiling_level(0)\n        self.db.system.profile.drop()\n        self.db.set_profiling_level(2)\n\n    def _resets_profiling(self):\n        self.db.set_profiling_level(self.initial_profiling_level)\n\n    def __enter__(self):\n        self._turn_on_profiling()\n        return self\n\n    def __exit__(self, t, value, traceback):\n        self._resets_profiling()\n\n    def __eq__(self, value):\n        counter = self._get_count()\n        return value == counter\n\n    def __ne__(self, value):\n        return not self.__eq__(value)\n\n    def __lt__(self, value):\n        return self._get_count() < value\n\n    def __le__(self, value):\n        return self._get_count() <= value\n\n    def __gt__(self, value):\n        return self._get_count() > value\n\n    def __ge__(self, value):\n        return self._get_count() >= value\n\n    def __int__(self):\n        return self._get_count()\n\n    def __repr__(self):\n        \"\"\"repr query_counter as the number of queries.\"\"\"\n        return u\"%s\" % self._get_count()\n\n    def _get_count(self):\n        \"\"\"Get the number of queries by counting the current number of entries in db.system.profile\n        and substracting the queries issued by this context. In fact everytime this is called, 1 query is\n        issued so we need to balance that\n        \"\"\"\n        count = (\n            count_documents(self.db.system.profile, self._ignored_query)\n            - self._ctx_query_counter\n        )\n        self._ctx_query_counter += (\n            1  # Account for the query we just issued to gather the information\n        )\n        return count\n\n\n@contextmanager\ndef set_write_concern(collection, write_concerns):\n    combined_concerns = dict(collection.write_concern.document.items())\n    combined_concerns.update(write_concerns)\n    yield collection.with_options(write_concern=WriteConcern(**combined_concerns))\n", "path": "mongoengine/context_managers.py"}]}