neosqlite.collection.cursor module¶
- class neosqlite.collection.cursor.Cursor(collection: Collection, filter: dict[str, Any] | None = None, projection: dict[str, Any] | None = None, hint: str | None = None, session: ClientSession | None = None, tables_to_cleanup: list[str] | None = None)[source]¶
Bases:
objectClass representing a cursor for iterating over documents in a collection with applied filters, projections, sorting, and pagination.
- __init__(collection: Collection, filter: dict[str, Any] | None = None, projection: dict[str, Any] | None = None, hint: str | None = None, session: ClientSession | None = None, tables_to_cleanup: list[str] | None = None)[source]¶
Initialize a new cursor instance.
- Parameters:
collection (Collection) – The collection to operate on.
filter (dict[str, Any], optional) – Filter criteria to apply to the documents.
projection (dict[str, Any], optional) – Projection criteria to specify which fields to include.
hint (str, optional) – Hint for the database to improve query performance.
session (ClientSession, optional) – A ClientSession for transactions.
tables_to_cleanup (list[str], optional) – List of temporary tables to drop when closed.
- max_await_time_ms(max_await_time_ms: int | None) Cursor[source]¶
Set the maximum time to wait for new documents (for tailable cursors).
- Parameters:
max_await_time_ms (int, optional) – The maximum time to wait in milliseconds.
- Returns:
The cursor object with the max_await_time_ms applied.
- Return type:
- add_option(mask: int) Cursor[source]¶
Set query flags (bitmask) for this cursor.
- Parameters:
mask (int) – The bitmask of options to set.
- Returns:
The cursor object with the options applied.
- Return type:
- remove_option(mask: int) Cursor[source]¶
Unset query flags (bitmask) for this cursor.
- Parameters:
mask (int) – The bitmask of options to unset.
- Returns:
The cursor object with the options removed.
- Return type:
- property session: Any | None¶
Get the ClientSession associated with this cursor.
- Returns:
The ClientSession, or None if no session is associated.
- Return type:
Any | None
- property cursor_id: int¶
Get the ID of this cursor.
- Returns:
The cursor ID (always 0 for NeoSQLite).
- Return type:
int
- limit(limit: int) Cursor[source]¶
Limit the number of documents returned by the cursor.
- Parameters:
limit (int) – The maximum number of documents to return.
- Returns:
The cursor object with the limit applied.
- Return type:
- skip(skip: int) Cursor[source]¶
Skip the specified number of documents when iterating over the cursor.
- Parameters:
skip (int) – The number of documents to skip.
- Returns:
The cursor object with the skip applied.
- Return type:
- sort(key_or_list: str | list[tuple], direction: int | None = None) Cursor[source]¶
Sort the documents returned by the cursor.
- Parameters:
key_or_list (str | list[tuple]) – The key or list of keys to sort by.
direction (int, optional) – The sorting direction (ASCENDING or DESCENDING). Defaults to ASCENDING if None.
- Returns:
The cursor object with the sorting applied.
- Return type:
- batch_size(size: int) Cursor[source]¶
Set the batch size for the cursor.
MongoDB-compatible batchSize parameter for controlling memory usage. Results are fetched from the database in batches of the specified size.
- Parameters:
size (int) – The batch size (default: 101, matches MongoDB)
- Returns:
The cursor object for chaining
- Return type:
Example
>>> cursor = collection.find().batch_size(50)
- hint(hint: str | list[tuple[str, int]]) Cursor[source]¶
Set the index hint for the cursor.
- Parameters:
hint – The index name (str) or list of (field, direction) tuples
- Returns:
The cursor object with the hint applied
- Return type:
- min(min_spec: list[tuple[str, Any]] | tuple[str, Any]) Cursor[source]¶
Set the minimum bound for index queries.
This method sets a lower bound on the index values to be scanned. Only documents with index values greater than or equal to the specified minimum will be returned.
- Parameters:
min_spec – A list of (field, value) tuples specifying the inclusive lower bound, e.g., [(“age”, 18)]
- Returns:
The cursor object with the minimum bound applied
- Return type:
- Raises:
TypeError – If min_spec is not a list or tuple
Example
>>> cursor = collection.find({"age": {"$gte": 18}}).min([("age", 18)])
- max(max_spec: list[tuple[str, Any]] | tuple[str, Any]) Cursor[source]¶
Set the maximum bound for index queries.
This method sets an upper bound on the index values to be scanned. Only documents with index values less than the specified maximum will be returned.
- Parameters:
max_spec – A list of (field, value) tuples specifying the exclusive upper bound, e.g., [(“age”, 65)]
- Returns:
The cursor object with the maximum bound applied
- Return type:
- Raises:
TypeError – If max_spec is not a list or tuple
Example
>>> cursor = collection.find({"age": {"$lte": 65}}).max([("age", 65)])
- collation(collation: dict[str, Any]) Cursor[source]¶
Set the collation for the cursor.
Collation allows users to specify language-specific rules for string comparison, such as rules for lettercase and accent marks.
- Parameters:
collation (dict[str, Any]) – A dictionary specifying collation options: - locale (str): Language locale (e.g., “en_US”, “fr_FR”, “de_DE”) - caseLevel (bool): Whether to include case comparison - caseFirst (str): “upper”, “lower”, or “off” - strength (int): Comparison strength (1-5) - numericOrdering (bool): Compare numbers numerically - alternate (str): “shifted” or “non-ignorable” - backwards (bool): Sort backwards (for French)
- Returns:
The cursor object with the collation applied
- Return type:
Example
>>> cursor = collection.find({"name": {"$gte": "A"}}).collation( ... {"locale": "fr_FR", "strength": 2} ... )
Note
NeoSQLite maps common locales to SQLite collations: - Default/unknown: BINARY (case-sensitive) - Locales with case-insensitive: NOCASE - Custom collations can be registered via Connection tokenizers
- where(predicate: Callable[[dict[str, Any]], bool]) Cursor[source]¶
Filter cursor results using a Python predicate function.
This is a Tier-3 (Python fallback) method that applies a Python function to filter documents after they are retrieved from the database.
- Parameters:
predicate (Callable[[dict[str, Any]], bool]) – A function that takes a document and returns True if the document should be included.
- Returns:
The cursor object with the predicate applied
- Return type:
Example
>>> def is_high_value(doc): ... return doc.get('value', 0) > 10 >>> cursor = collection.find({}).where(is_high_value)
Note
This method uses Python-based filtering (Tier-3), which means all matching documents are retrieved from the database first, then filtered in Python. For better performance, use MongoDB-style query operators in the find() filter when possible.
- comment(comment: str) Cursor[source]¶
Add a comment to the query for debugging and profiling.
The comment is injected as a SQL comment in the generated query, which can be useful for query profiling and debugging.
- Parameters:
comment (str) – The comment text to add to the query
- Returns:
The cursor object with the comment applied
- Return type:
Example
>>> cursor = collection.find({"age": {"$gte": 18}}).comment("find adults")
- to_list(length: int | None = None) list[dict[str, Any]][source]¶
Convert the cursor to a list of documents.
This method efficiently converts the cursor contents to a list. If length is specified, returns at most that many documents.
- Parameters:
length (int, optional) – Maximum number of documents to return. If None, returns all documents.
- Returns:
List of documents in the cursor
- Return type:
list[dict[str, Any]]
Example
>>> cursor = collection.find({"age": {"$gte": 18}}) >>> adults = cursor.to_list() >>> first_5 = cursor.to_list(5)
- clone() Cursor[source]¶
Create a clone of this cursor with the same options.
Returns a new cursor with the same filter, projection, hint, sort, skip, and limit settings. The clone is unevaluated and can be iterated independently.
- Returns:
A new cursor with the same settings
- Return type:
Example
>>> cursor = collection.find({"age": {"$gte": 18}}).limit(10) >>> clone = cursor.clone() >>> results1 = list(cursor) >>> results2 = list(clone)
- property retrieved: int¶
Return the number of documents retrieved from the cursor.
This property tracks how many documents have been iterated over since the cursor was created or last reset.
- Returns:
The number of documents retrieved so far
- Return type:
int
Example
>>> cursor = collection.find({}).limit(10) >>> docs = list(cursor) >>> cursor.retrieved 10
- property alive: bool¶
Check if the cursor has more documents to iterate.
In NeoSQLite, a cursor is considered alive if it hasn’t been fully exhausted. This is a simplified implementation for PyMongo API compatibility.
- Returns:
True if the cursor may have more documents, False if exhausted
- Return type:
bool
Note
NeoSQLite cursors are re-iterable, so this property tracks whether the current iteration has been completed.
Example
>>> cursor = collection.find({}).limit(10) >>> cursor.alive True >>> list(cursor) >>> cursor.alive False
- property collection¶
Return a reference to the collection this cursor is iterating over.
- Returns:
The collection associated with this cursor
- Return type:
Example
>>> cursor = collection.find({}) >>> cursor.collection Collection(database, "collection_name") >>> cursor.collection.name 'collection_name'
- property address: tuple | None¶
Return the address of the database.
For NeoSQLite, this returns a tuple representing the database connection. This is a simplified implementation for PyMongo API compatibility.
- Returns:
- A tuple of (database_path, 0) after iteration starts,
None before the cursor has been executed. - For file databases: (‘sqlite:///path/to/file.db’, 0) - For memory databases: (‘sqlite::memory:’, 0)
- Return type:
tuple | None
Note
SQLite is an embedded database without a server, so this returns the database path instead of a network address. Returns None until the cursor has been iterated, matching PyMongo behavior.
Example
>>> cursor = collection.find({}) >>> cursor.address # Before iteration None >>> list(cursor) >>> cursor.address # After iteration ('sqlite::memory:', 0) # or ('sqlite:///path/to/file.db', 0)
- explain(verbosity: str = 'queryPlanner') dict[str, Any][source]¶
Return the query execution plan.
Uses SQLite’s EXPLAIN QUERY PLAN to provide information about how the query will be executed, including index usage.
- Parameters:
verbosity (str) – Verbosity level - “executionStats” or “queryPlanner” (kept for PyMongo compatibility, SQLite always returns full plan) Defaults to “queryPlanner”.
- Returns:
- Query execution plan with the following structure:
- queryPlanner: Information about the query plan
winningPlan: List of plan stages
indexUsage: Information about index usage
- executionStats: Execution statistics (if verbosity=”executionStats”)
nReturned: Number of documents returned
executionTimeMillis: Execution time in milliseconds
- Return type:
dict[str, Any]
Example
>>> cursor = collection.find({"age": {"$gte": 18}}) >>> plan = cursor.explain() >>> print(plan['queryPlanner']['winningPlan'])
- _execute_query() Iterator[dict[str, Any]][source]¶
Execute the query and yield the results after applying filters, sorting, pagination, and projection.
- Yields:
dict[str, Any] – A dictionary representing each document in the result set.
- _get_filtered_documents() Iterable[dict[str, Any]][source]¶
Retrieve documents based on the filter criteria, applying SQL-based filtering where possible, or falling back to Python-based filtering for complex queries. For datetime queries, use the specialized datetime query processor.
- Returns:
- An iterable of dictionaries representing
the documents that match the filter criteria.
- Return type:
Iterable[dict[str, Any]]
- _handle_python_fallback() Iterable[dict[str, Any]][source]¶
Handle complex queries by filtering all documents in Python.
- _handle_expr_query() Iterable[dict[str, Any]][source]¶
Handle $expr queries with SQL evaluation when possible, Python fallback otherwise.
This method uses the query helper’s _build_expr_where_clause to attempt SQL evaluation (Tiers 1 and 2), and falls back to Python evaluation (Tier 3) if needed.
- _build_minmax_clause(where_clause: str, params: tuple, min_spec: dict[str, Any] | None, max_spec: dict[str, Any] | None) tuple[source]¶
Build SQL clause for min/max index bounds.
- Parameters:
where_clause – Existing WHERE clause (may be empty)
params – Existing parameters
min_spec – Minimum bound specification
max_spec – Maximum bound specification
- Returns:
Tuple of (new WHERE clause, new parameters)
- _get_collate_clause() str[source]¶
Get the SQL COLLATE clause based on collation settings.
- Returns:
COLLATE clause or empty string if no collation is set
- Return type:
str
Note
Maps MongoDB collation locales to SQLite collations: - Case-insensitive locales → NOCASE - Default/unknown → BINARY (case-sensitive) Custom collations can be registered via Connection tokenizers.
Note: COLLATE is applied to ORDER BY clauses, not WHERE clauses. For WHERE clause string comparisons, use _apply_collation_to_expr().
- _contains_datetime_operations(query: dict[str, Any]) bool[source]¶
Check if a query contains datetime operations that should use the datetime processor.
- Parameters:
query – MongoDB-style query dictionary
- Returns:
True if query contains datetime operations, False otherwise
- _is_datetime_value(value: Any) bool[source]¶
Check if a value is a datetime object or datetime string.
- Parameters:
value – Value to check
- Returns:
True if value is datetime-related, False otherwise
- _is_datetime_regex(pattern: str) bool[source]¶
Check if a regex pattern is likely to be for datetime matching.
- Parameters:
pattern – Regex pattern string
- Returns:
True if pattern is likely datetime-related, False otherwise
- _load_documents(rows) Iterable[dict[str, Any]][source]¶
Load documents from rows returned by the database query, including handling both id and _id.
- Parameters:
rows – Database result rows containing id, _id, and data
- Returns:
An iterable of loaded documents
- Return type:
Iterable[dict[str, Any]]
- _apply_sorting(docs: Iterable[dict[str, Any]]) list[dict[str, Any]][source]¶
Sort the documents based on the specified sorting criteria.
- Parameters:
docs (Iterable[dict[str, Any]]) – The iterable of documents to sort.
- Returns:
- A list of dictionaries representing the documents
sorted by the specified criteria.
- Return type:
list[dict[str, Any]]
- _apply_pagination(docs: Iterable[dict[str, Any]]) list[dict[str, Any]][source]¶
Apply skip and limit to the documents.
- Parameters:
docs (Iterable[dict[str, Any]]) – The iterable of documents to apply pagination to.
- Returns:
- A list of dictionaries representing the documents
after applying skip and limit.
- Return type:
list[dict[str, Any]]
- _apply_projection(docs: Iterable[dict[str, Any]]) list[dict[str, Any]][source]¶
Apply projection to the documents.
- Parameters:
docs (Iterable[dict[str, Any]]) – The iterable of documents to apply projection to.
- Returns:
- A list of dictionaries representing the documents
after applying the projection.
- Return type:
list[dict[str, Any]]