0
# Cursors and Result Iteration
1
2
Cursor management for query results with support for sorting, limiting, skipping, and batch processing of result sets. Cursors provide efficient iteration over query results with chainable operations.
3
4
## Capabilities
5
6
### Cursor Creation and Iteration
7
8
Cursors are created by find operations and provide iterator interface for accessing results.
9
10
```python { .api }
11
class Cursor:
12
def __iter__(self):
13
"""
14
Iterator interface for cursor.
15
16
Returns:
17
Iterator[dict]: iterator over documents
18
"""
19
20
def __next__(self):
21
"""
22
Get next document.
23
24
Returns:
25
dict: next document
26
27
Raises:
28
StopIteration: when no more documents
29
"""
30
31
def next(self):
32
"""
33
Get next document (Python 2 compatibility).
34
35
Returns:
36
dict: next document
37
38
Raises:
39
StopIteration: when no more documents
40
"""
41
```
42
43
**Usage Example:**
44
45
```python
46
collection = mongomock.MongoClient().db.users
47
48
# Get cursor from find operation
49
cursor = collection.find({'age': {'$gte': 18}})
50
51
# Iterate over results
52
for document in cursor:
53
print(f"User: {document['name']}, Age: {document['age']}")
54
55
# Convert to list
56
users = list(collection.find({'status': 'active'}))
57
```
58
59
### Result Ordering
60
61
Sort query results using single or multiple sort criteria with ascending or descending order.
62
63
```python { .api }
64
def sort(self, key_or_list, direction=None):
65
"""
66
Sort the cursor results.
67
68
Parameters:
69
- key_or_list: str or list, sort key or list of (key, direction) tuples
70
- direction: int, sort direction (1 for ascending, -1 for descending)
71
72
Returns:
73
Cursor: cursor with sorting applied
74
"""
75
```
76
77
**Usage Example:**
78
79
```python
80
from mongomock import ASCENDING, DESCENDING
81
82
collection = mongomock.MongoClient().db.users
83
84
# Sort by single field
85
cursor = collection.find().sort('age', ASCENDING)
86
cursor = collection.find().sort('name', DESCENDING)
87
88
# Sort by multiple fields
89
cursor = collection.find().sort([
90
('age', DESCENDING),
91
('name', ASCENDING)
92
])
93
94
# Alternative syntax
95
cursor = collection.find().sort('age', 1) # Ascending
96
cursor = collection.find().sort('age', -1) # Descending
97
98
# Chain sorting with other operations
99
results = list(
100
collection.find({'status': 'active'})
101
.sort('created_at', -1)
102
.limit(10)
103
)
104
```
105
106
### Result Limiting and Skipping
107
108
Control the number of results returned and implement pagination through skip and limit operations.
109
110
```python { .api }
111
def skip(self, count):
112
"""
113
Skip the specified number of documents.
114
115
Parameters:
116
- count: int, number of documents to skip
117
118
Returns:
119
Cursor: cursor with skip applied
120
"""
121
122
def limit(self, count):
123
"""
124
Limit the number of returned documents.
125
126
Parameters:
127
- count: int, maximum number of documents to return
128
129
Returns:
130
Cursor: cursor with limit applied
131
"""
132
```
133
134
**Usage Example:**
135
136
```python
137
collection = mongomock.MongoClient().db.users
138
139
# Get first 10 results
140
first_page = list(collection.find().limit(10))
141
142
# Skip first 10, get next 10 (pagination)
143
second_page = list(collection.find().skip(10).limit(10))
144
145
# Get top 5 oldest users
146
oldest_users = list(
147
collection.find()
148
.sort('birth_date', 1)
149
.limit(5)
150
)
151
152
# Complex pagination
153
page_size = 20
154
page_number = 3
155
page_results = list(
156
collection.find({'status': 'active'})
157
.sort('created_at', -1)
158
.skip((page_number - 1) * page_size)
159
.limit(page_size)
160
)
161
```
162
163
### Batch Processing
164
165
Configure batch size for efficient memory usage when processing large result sets.
166
167
```python { .api }
168
def batch_size(self, count):
169
"""
170
Set the cursor batch size.
171
172
Parameters:
173
- count: int, number of documents per batch
174
175
Returns:
176
Cursor: cursor with batch size configured
177
"""
178
```
179
180
**Usage Example:**
181
182
```python
183
collection = mongomock.MongoClient().db.large_collection
184
185
# Process large dataset with controlled batch size
186
cursor = collection.find().batch_size(100)
187
188
for document in cursor:
189
# Process each document
190
process_document(document)
191
```
192
193
### Query Hints and Optimization
194
195
Provide hints to query planner and control query execution behavior.
196
197
```python { .api }
198
def hint(self, hint):
199
"""
200
Provide a hint to the query planner.
201
202
Parameters:
203
- hint: str or list, index hint specification
204
205
Returns:
206
Cursor: cursor with hint applied
207
"""
208
209
def max_time_ms(self, max_time_ms):
210
"""
211
Set maximum execution time for the query.
212
213
Parameters:
214
- max_time_ms: int, maximum execution time in milliseconds
215
216
Returns:
217
Cursor: cursor with time limit applied
218
"""
219
220
def allow_disk_use(self, allow_disk_use=False):
221
"""
222
Allow query to use disk for sorting large result sets.
223
224
Parameters:
225
- allow_disk_use: bool, whether to allow disk usage
226
227
Returns:
228
Cursor: cursor with disk usage setting applied
229
"""
230
```
231
232
**Usage Example:**
233
234
```python
235
collection = mongomock.MongoClient().db.users
236
237
# Use index hint
238
cursor = collection.find({'email': 'user@example.com'}).hint('email_1')
239
240
# Set query timeout
241
cursor = collection.find().max_time_ms(5000) # 5 second timeout
242
243
# Allow disk usage for large sorts
244
cursor = collection.find().sort('created_at', -1).allow_disk_use(True)
245
246
# Combine optimization options
247
optimized_cursor = (
248
collection.find({'status': 'active'})
249
.hint('status_1_created_at_-1')
250
.max_time_ms(10000)
251
.batch_size(50)
252
)
253
```
254
255
### Cursor Management
256
257
Control cursor lifecycle and state management operations.
258
259
```python { .api }
260
def close(self):
261
"""
262
Close the cursor and free resources.
263
264
Returns:
265
None
266
"""
267
268
def clone(self):
269
"""
270
Create a copy of the cursor.
271
272
Returns:
273
Cursor: cloned cursor instance
274
"""
275
276
def rewind(self):
277
"""
278
Rewind cursor to beginning.
279
280
Returns:
281
Cursor: rewound cursor
282
"""
283
284
def collation(self, collation=None):
285
"""
286
Set collation for the cursor.
287
288
Parameters:
289
- collation: dict, collation specification
290
291
Returns:
292
Cursor: cursor with collation applied
293
"""
294
```
295
296
**Usage Example:**
297
298
```python
299
collection = mongomock.MongoClient().db.users
300
301
# Create cursor
302
cursor = collection.find({'status': 'active'})
303
304
# Clone cursor for reuse
305
cursor_copy = cursor.clone()
306
307
# Process first set of results
308
first_results = list(cursor.limit(10))
309
310
# Rewind and process again
311
cursor.rewind()
312
second_results = list(cursor.limit(5))
313
314
# Close cursor when done
315
cursor.close()
316
317
# Use collation for text sorting
318
text_cursor = collection.find().collation({
319
'locale': 'en_US',
320
'strength': 2 # Case insensitive
321
})
322
```
323
324
### Cursor Properties
325
326
Access cursor state and configuration information.
327
328
```python { .api }
329
@property
330
def alive(self):
331
"""
332
bool: whether cursor is still active and has more results
333
"""
334
335
@property
336
def cursor_id(self):
337
"""
338
int: unique cursor identifier
339
"""
340
341
@property
342
def address(self):
343
"""
344
tuple: server address (always None in mongomock)
345
"""
346
```
347
348
**Usage Example:**
349
350
```python
351
collection = mongomock.MongoClient().db.users
352
cursor = collection.find()
353
354
# Check if cursor has more results
355
if cursor.alive:
356
next_doc = next(cursor)
357
358
print(f"Cursor ID: {cursor.cursor_id}")
359
print(f"Server address: {cursor.address}")
360
```
361
362
### Distinct Values
363
364
Get distinct values for a field across the cursor results.
365
366
```python { .api }
367
def distinct(self, key, session=None):
368
"""
369
Get distinct values for a field.
370
371
Parameters:
372
- key: str, field name to get distinct values for
373
- session: ClientSession, session to use (ignored)
374
375
Returns:
376
list: list of distinct values
377
"""
378
```
379
380
**Usage Example:**
381
382
```python
383
collection = mongomock.MongoClient().db.users
384
385
# Get distinct values from cursor
386
cursor = collection.find({'status': 'active'})
387
distinct_ages = cursor.distinct('age')
388
distinct_departments = cursor.distinct('department')
389
390
print(f"Distinct ages: {distinct_ages}")
391
print(f"Distinct departments: {distinct_departments}")
392
```
393
394
## Constants
395
396
```python { .api }
397
# Sort directions (from mongomock.helpers)
398
ASCENDING = 1
399
DESCENDING = -1
400
401
# Cursor types
402
class CursorType:
403
NON_TAILABLE = 0
404
TAILABLE = 2
405
TAILABLE_AWAIT = 130
406
EXHAUST = 64
407
```