Skip to content

Firestore reference

At a glance

Firestore

Method Gives back Notes
Firestore.firestore() Firestore The shared client
collection_with_path(path) CollectionReference
document_with_path(path) DocumentReference Full path, like "cities/LA"
collection_group_with_id(id) Query Pass only the collection name
use_emulator(host="127.0.0.1", port=8080) nothing Before any other call; development only
batch() WriteBatch
run_transaction(update_fn, callback=None) nothing Callback gets (result, error)

CollectionReference (also a Query)

Member Notes
collection_id, path, parent parent is a DocumentReference or None
document_with_path(path) Short path, like "LA"
document_with_auto_id() New reference with a generated ID. Nothing is saved
add_document_with_data(data, callback=None) Callback gets (document_reference, error)

Query

Filters (each gives a new Query):

  • query_where_field_is_equal_to(field, value)
  • query_where_field_is_not_equal_to(field, value)
  • query_where_field_is_less_than(field, value)
  • query_where_field_is_less_than_or_equal_to(field, value)
  • query_where_field_is_greater_than(field, value)
  • query_where_field_is_greater_than_or_equal_to(field, value)
  • query_where_field_array_contains(field, value)
  • query_where_field_array_contains_any(field, values)
  • query_where_field_in(field, values)
  • query_where_field_not_in(field, values)
  • query_where_filter(filter)

Order and limit (each gives a new Query):

  • query_ordered_by_field(field, descending=False)
  • query_limited_to(limit), query_limited_to_last(limit)
  • query_starting_at_values(values), query_starting_after_values(values)
  • query_ending_at_values(values), query_ending_before_values(values)
  • query_starting_at_document(snapshot), query_starting_after_document(snapshot)
  • query_ending_at_document(snapshot), query_ending_before_document(snapshot)

Run the query:

Method Callback
get_documents(callback, source=None) (QuerySnapshot, error)
add_snapshot_listener(callback, include_metadata_changes=False, options=None) (QuerySnapshot, error), returns ListenerRegistration

Aggregates: count (property) and aggregate(fields) give an AggregateQuery.

QuerySnapshot

  • documents: list of DocumentSnapshot (also len(), [i], for ... in)
  • document_changes: list of DocumentChange
  • document_changes_with_include_metadata_changes(bool)
  • is_empty, count, metadata, query

DocumentReference

Member Notes
document_id, path, parent, firestore parent is a CollectionReference
collection_with_path(path) A sub collection
get_document(callback, source=None) Callback gets (DocumentSnapshot, error)
set_data(data, merge=False, callback=None) Callback gets (error)
set_data_merge_fields(data, fields, callback=None) Callback gets (error)
update_data(data, callback=None) The document must exist. Callback gets (error)
delete_document(callback=None) Callback gets (error)
add_snapshot_listener(callback, include_metadata_changes=False, options=None) Callback gets (DocumentSnapshot, error). Returns ListenerRegistration

DocumentSnapshot

  • document_id, exists, reference, metadata
  • data: a dict of Python values ({} if the document does not exist)
  • data_with_server_timestamp_behavior(behavior)
  • get(field) / snapshot[field]: one field, dotted names allowed

DocumentChange

  • type: one of DocumentChange.ADDED, DocumentChange.MODIFIED, DocumentChange.REMOVED
  • document: a DocumentSnapshot
  • old_index, new_index

ListenerRegistration and SnapshotListenOptions

  • remove(): stops the updates. It is safe to call twice.
  • SnapshotListenOptions(include_metadata_changes=False, source=None)

SnapshotMetadata

  • is_from_cache, has_pending_writes

WriteBatch

  • set_data(data, document, merge=False)
  • set_data_merge_fields(data, document, fields)
  • update_data(data, document)
  • delete_document(document)
  • commit(callback=None): callback gets (error)

All except commit give back the batch, so you can chain them.

Transaction

Given to your function inside run_transaction.

  • get_document(document) gives a DocumentSnapshot
  • set_data(data, document, merge=False)
  • update_data(data, document)
  • delete_document(document)

FieldValue

  • field_value_for_delete()
  • field_value_for_server_timestamp()
  • field_value_for_array_union(elements)
  • field_value_for_array_remove(elements)
  • field_value_for_integer_increment(value)
  • field_value_for_double_increment(value)

Filter

  • filter_where_field_is_equal_to(field, value)
  • filter_where_field_is_not_equal_to(field, value)
  • filter_where_field_is_less_than(field, value)
  • filter_where_field_is_less_than_or_equal_to(field, value)
  • filter_where_field_is_greater_than(field, value)
  • filter_where_field_is_greater_than_or_equal_to(field, value)
  • filter_where_field_array_contains(field, value)
  • filter_where_field_array_contains_any(field, values)
  • filter_where_field_in(field, values)
  • filter_where_field_not_in(field, values)
  • or_filter_with_filters(filters)
  • and_filter_with_filters(filters)

AggregateField, AggregateQuery, AggregateQuerySnapshot

  • AggregateField.aggregate_field_for_count()
  • AggregateField.aggregate_field_for_sum_of_field(field)
  • AggregateField.aggregate_field_for_average_of_field(field)
  • AggregateQuery.aggregation_with_source(source, callback): callback gets (snapshot, error)
  • snapshot.count: the count, as an int
  • snapshot.value_for_aggregate_field(field): an int, a float, or None

Enum values

Some Firebase names are fixed numbers in the compiled SDK, and Python cannot look them up by name. They are kept in pyios_firebase/firestore/enums.py:

Class Values
FIRFirestoreSource Default, Server, Cache
FIRServerTimestampBehavior None_, Estimate, Previous
FIRAggregateSource Server
FIRListenSource Default, Cache
FIRDocumentChangeType Added, Modified, Removed

If you update the Firebase SDK, check these values in the SDK header files.

pyios_firebase.firestore

Cloud Firestore.

from pyios_firebase.firestore import Firestore

db = Firestore.firestore()
db.collection_with_path("cities").document_with_path("LA").set_data({"name": "Los Angeles"})

Needs the FirebaseFirestore framework.

Modules:

Name Description
aggregate

Aggregate queries: count, sum and average, calculated on the server.

collection_reference

CollectionReference: a collection, and a query over all its documents.

document_change

DocumentChange: one change between two snapshots of a query.

document_reference

DocumentReference: points to one document; reads, writes and listens to it.

document_snapshot

DocumentSnapshot: the data of one document, as read at one moment.

enums

Firestore enum values.

field_value

FieldValue: special values the server applies (increment, delete, ...).

filter

Filter: conditions for queries, which can be combined with OR and AND.

firestore

Firestore: the Cloud Firestore client; entry point for everything else.

listener_registration

Snapshot listener handles (ListenerRegistration) and options.

query

Query: filters, order, limits and cursors, then reads or listens.

query_snapshot

QuerySnapshot: the result of a query, usable like a list.

snapshot_metadata

SnapshotMetadata: whether a snapshot came from the cache.

transaction

Transaction: atomic reads and writes inside Firestore.run_transaction.

write_batch

WriteBatch: many writes that all succeed or all fail.

Classes:

Name Description
Firestore

The app's Cloud Firestore client. Get it with Firestore.firestore().

AggregateField

One value to calculate in Query.aggregate: a count, a sum or an average.

AggregateQuery

A count, sum or average, calculated on the server without downloading

AggregateQuerySnapshot

The result of an aggregate query.

CollectionReference

A collection. It is also a Query for all of its documents.

DocumentChange

One change in a QuerySnapshot: a document was added, modified or

DocumentReference

Points to one document. It holds no data: read it with get_document.

DocumentSnapshot

The data of one document, as read at one moment.

FIRAggregateSource

Where aggregate queries (count, sum, average) are calculated.

FIRDocumentChangeType

The raw values behind DocumentChange.type.

FIRFirestoreSource

Where get_document / get_documents read from.

FIRListenSource

Where a snapshot listener gets its data.

FIRServerTimestampBehavior

What a server timestamp that is still pending reads as, before the

FieldValue

Special values for set_data / update_data: the server applies

Filter

A condition for Query.query_where_filter.

ListenerRegistration

Given back by every add_snapshot_listener. Call remove() to stop.

SnapshotListenOptions

Options for add_snapshot_listener(options=...).

Query

A query over a collection (or a collection group).

QuerySnapshot

The result of a query. You can use it like a list of DocumentSnapshot::

SnapshotMetadata

Where a snapshot's data came from.

Transaction

Given to your function inside Firestore.run_transaction.

TransactionException

Raise inside a run_transaction function to stop the transaction.

WriteBatch

Many writes saved together: all of them work, or none do.

Firestore

Firestore(db: ObjCObject | None = None)

The app's Cloud Firestore client. Get it with Firestore.firestore().

::

db = Firestore.firestore()
db.collection_with_path("cities").document_with_path("LA").set_data({"name": "LA"})

Parameters:

Name Type Description Default
db ObjCObject | None

the native FIRFirestore. Leave it out: Firestore() gives the same client as Firestore.firestore().

None

Methods:

Name Description
firestore

The shared client for the default Firebase app.

use_emulator

Send this client's reads and writes to the local Firestore emulator.

batch

A new WriteBatch.

collection_with_path

A collection, by path.

collection_group_with_id

Every collection named collection_id, wherever it is in the database.

document_with_path

A document, by its full path.

run_transaction

Read and write documents atomically.

firestore classmethod

firestore() -> Firestore

The shared client for the default Firebase app.

use_emulator

use_emulator(
    host: str = "127.0.0.1", port: int = 8080
) -> None

Send this client's reads and writes to the local Firestore emulator.

Points the client at host:port and turns TLS off, since the emulator speaks plain HTTP/2. Call it once, right after core.configure() and before any other use of Firestore (the SDK fixes its settings on first use). Use it only in development and test builds.

::

core.configure()
Firestore.firestore().use_emulator("127.0.0.1", 8080)

Parameters:

Name Type Description Default
host str

the emulator's host. "127.0.0.1" works in the iOS Simulator, which shares the Mac's network; on a device, use the Mac's LAN address and start the emulator with "host": "0.0.0.0".

'127.0.0.1'
port int

the emulator's port (firebase emulators:start uses 8080).

8080

batch

batch() -> WriteBatch

A new WriteBatch.

collection_with_path

collection_with_path(path: str) -> CollectionReference

A collection, by path.

Parameters:

Name Type Description Default
path str

a slash-separated path with an odd number of parts, for example "cities" or "cities/SF/landmarks".

required

Returns:

Type Description
CollectionReference

A CollectionReference. Nothing is read yet.

collection_group_with_id

collection_group_with_id(collection_id: str) -> Query

Every collection named collection_id, wherever it is in the database.

Collection group queries often need an index; the error message has a link that creates it.

Parameters:

Name Type Description Default
collection_id str

the collection's name only ("landmarks"), not a path. It must not contain /.

required

Returns:

Type Description
Query

A Query over all the documents of those collections.

document_with_path

document_with_path(path: str) -> DocumentReference

A document, by its full path.

Parameters:

Name Type Description Default
path str

a slash-separated path with an even number of parts, for example "cities/LA" or "cities/LA/landmarks/griffith".

required

Returns:

Type Description
DocumentReference

A DocumentReference. Nothing is read yet.

run_transaction

run_transaction(
    update_fn: Callable[[Transaction], T],
    callback: ResultCallback[T] | None = None,
) -> None

Read and write documents atomically.

update_fn(transaction) may run more than once (when the data it read changed before the commit), so it must only read and write through transaction: no other side effects.

Parameters:

Name Type Description Default
update_fn Callable[[Transaction], T]

reads with transaction.get_document first, then writes. Raise an exception to stop the transaction. What it returns (any Python value) is given to callback.

required
callback ResultCallback[T] | None

gets (result, None) after the commit, or (None, error).

None

AggregateField

AggregateField(field: ObjCObject)

One value to calculate in Query.aggregate: a count, a sum or an average.

Make them with the static methods; you do not call AggregateField(...) yourself.

Parameters:

Name Type Description Default
field ObjCObject

the native FIRAggregateField.

required

Methods:

Name Description
aggregate_field_for_count

The number of documents.

aggregate_field_for_sum_of_field

The sum of a number field over the matching documents.

aggregate_field_for_average_of_field

The average of a number field over the matching documents.

aggregate_field_for_count staticmethod

aggregate_field_for_count() -> AggregateField

The number of documents.

aggregate_field_for_sum_of_field staticmethod

aggregate_field_for_sum_of_field(
    field: str,
) -> AggregateField

The sum of a number field over the matching documents.

Documents without the field, or with a value that is not a number, are skipped.

Parameters:

Name Type Description Default
field str

the field name (dotted for a nested field).

required

Returns:

Type Description
AggregateField

An AggregateField for Query.aggregate.

aggregate_field_for_average_of_field staticmethod

aggregate_field_for_average_of_field(
    field: str,
) -> AggregateField

The average of a number field over the matching documents.

Documents without the field, or with a value that is not a number, are skipped. With no such documents the average is None.

Parameters:

Name Type Description Default
field str

the field name (dotted for a nested field).

required

Returns:

Type Description
AggregateField

An AggregateField for Query.aggregate.

AggregateQuery

AggregateQuery(ref: ObjCObject)

A count, sum or average, calculated on the server without downloading the documents. Made by Query.count or Query.aggregate.

Parameters:

Name Type Description Default
ref ObjCObject

the native FIRAggregateQuery.

required

Methods:

Name Description
aggregation_with_source

Run the aggregation.

aggregation_with_source

aggregation_with_source(
    source: int,
    callback: ResultCallback[AggregateQuerySnapshot],
) -> None

Run the aggregation.

Parameters:

Name Type Description Default
source int

FIRAggregateSource.Server.

required
callback ResultCallback[AggregateQuerySnapshot]

gets (AggregateQuerySnapshot, None) or (None, error).

required

AggregateQuerySnapshot

AggregateQuerySnapshot(snapshot: ObjCObject)

The result of an aggregate query.

Parameters:

Name Type Description Default
snapshot ObjCObject

the native FIRAggregateQuerySnapshot.

required

Methods:

Name Description
value_for_aggregate_field

The value calculated for one of the query's fields.

Attributes:

Name Type Description
count int

The number of documents (for Query.count).

count property

count: int

The number of documents (for Query.count).

value_for_aggregate_field

value_for_aggregate_field(
    aggregate_field: AggregateField,
) -> int | float | None

The value calculated for one of the query's fields.

Parameters:

Name Type Description Default
aggregate_field AggregateField

one of the AggregateField objects given to Query.aggregate (the same object, or an equal one).

required

Returns:

Type Description
int | float | None

An int (counts, sums of integers), a float, or None (for

int | float | None

example the average of no documents).

CollectionReference

CollectionReference(
    ref: ObjCObject, _state: QueryState | None = None
)

Bases: Query

A collection. It is also a Query for all of its documents.

Methods:

Name Description
document_with_path

A document in this collection.

document_with_auto_id

A new DocumentReference with a generated ID. Nothing is saved yet.

add_document_with_data

Create a document with a generated ID.

Attributes:

Name Type Description
collection_id str

The last part of the path. For "cities/SF/landmarks" it is "landmarks".

path str

The full path, for example "cities" or "cities/SF/landmarks".

parent DocumentReference | None

The document that holds this collection, or None at the top level.

collection_id property

collection_id: str

The last part of the path. For "cities/SF/landmarks" it is "landmarks".

path property

path: str

The full path, for example "cities" or "cities/SF/landmarks".

parent property

parent: DocumentReference | None

The document that holds this collection, or None at the top level.

document_with_path

document_with_path(path: str) -> DocumentReference

A document in this collection.

Parameters:

Name Type Description Default
path str

the document's ID ("SF"), or a path below this collection with an odd number of parts ("SF/landmarks/griffith").

required

Returns:

Type Description
DocumentReference

A DocumentReference. Nothing is read yet.

document_with_auto_id

document_with_auto_id() -> DocumentReference

A new DocumentReference with a generated ID. Nothing is saved yet.

add_document_with_data

add_document_with_data(
    data: FirestoreData,
    callback: ResultCallback[DocumentReference]
    | None = None,
) -> DocumentReference

Create a document with a generated ID.

Parameters:

Name Type Description Default
data FirestoreData

the fields (Python values; see to_firestore).

required
callback ResultCallback[DocumentReference] | None

gets (DocumentReference, None) once the server has the write, or (None, error).

None

Returns:

Type Description
DocumentReference

The new DocumentReference, right away (before the write ends).

Raises:

Type Description
TypeError

data holds a value Firestore cannot store.

DocumentChange

DocumentChange(change: ObjCObject)

One change in a QuerySnapshot: a document was added, modified or removed since the previous snapshot.

Changes come from QuerySnapshot.document_changes; you do not make them yourself.

Parameters:

Name Type Description Default
change ObjCObject

the native FIRDocumentChange.

required

Attributes:

Name Type Description
type ChangeType

DocumentChange.ADDED, MODIFIED or REMOVED.

document DocumentSnapshot

The document after the change (before it, for REMOVED).

old_index int

The document's position in the previous snapshot (a very large

new_index int

The document's position in this snapshot (NSNotFound for REMOVED).

type property

type: ChangeType

DocumentChange.ADDED, MODIFIED or REMOVED.

document property

document: DocumentSnapshot

The document after the change (before it, for REMOVED).

old_index property

old_index: int

The document's position in the previous snapshot (a very large number, NSNotFound, for ADDED).

new_index property

new_index: int

The document's position in this snapshot (NSNotFound for REMOVED).

DocumentReference

DocumentReference(ref: ObjCObject)

Points to one document. It holds no data: read it with get_document.

Data you write is converted with to_firestore (datetime, None, nested dicts and lists all work). A value Firestore cannot store raises TypeError before anything is sent.

You get references from Firestore, CollectionReference and snapshots; you do not make them yourself.

Parameters:

Name Type Description Default
ref ObjCObject

the native FIRDocumentReference.

required

Methods:

Name Description
collection_with_path

A sub collection of this document.

set_data

Write the document, creating it if needed.

set_data_merge_fields

Write only fields from data, keeping every other field.

update_data

Change only the given fields. The document must exist (use

delete_document

Delete the document. Its sub collections are NOT deleted.

get_document

Read the document once.

add_snapshot_listener

Listen to the document: callback runs now, then on every change.

Attributes:

Name Type Description
document_id str

The document's ID (the last part of its path).

path str

The full path, for example "cities/SF".

parent CollectionReference

The collection this document is in.

firestore Firestore

The Firestore client.

document_id property

document_id: str

The document's ID (the last part of its path).

path property

path: str

The full path, for example "cities/SF".

parent property

The collection this document is in.

firestore property

firestore: Firestore

The Firestore client.

collection_with_path

collection_with_path(path: str) -> CollectionReference

A sub collection of this document.

Parameters:

Name Type Description Default
path str

the collection's name ("landmarks"), or a path below this document with an odd number of parts.

required

Returns:

Type Description
CollectionReference

A CollectionReference. Nothing is read yet.

set_data

set_data(
    data: FirestoreData,
    merge: bool | ErrorCallback = False,
    callback: ErrorCallback | None = None,
) -> None

Write the document, creating it if needed.

Parameters:

Name Type Description Default
data FirestoreData

the fields.

required
merge bool | ErrorCallback

False replaces the whole document; True keeps the fields not in data. (A callback here is also accepted, for the old set_data(data, callback) form.)

False
callback ErrorCallback | None

gets None once the server has the write, or the error.

None

set_data_merge_fields

set_data_merge_fields(
    data: FirestoreData,
    fields: Sequence[str],
    callback: ErrorCallback | None = None,
) -> None

Write only fields from data, keeping every other field.

Parameters:

Name Type Description Default
data FirestoreData

the fields.

required
fields Sequence[str]

the field names to write (dotted names for nested fields).

required
callback ErrorCallback | None

gets None or the error.

None

update_data

update_data(
    data: FirestoreData,
    callback: ErrorCallback | None = None,
) -> None

Change only the given fields. The document must exist (use set_data(..., merge=True) to create it if missing).

Parameters:

Name Type Description Default
data FirestoreData

the fields to change. Dotted names ("address.city") change one nested field.

required
callback ErrorCallback | None

gets None or the error (NOT_FOUND if the document does not exist).

None

delete_document

delete_document(
    callback: ErrorCallback | None = None,
) -> None

Delete the document. Its sub collections are NOT deleted.

Parameters:

Name Type Description Default
callback ErrorCallback | None

gets None or the error. Deleting a missing document is not an error.

None

get_document

get_document(
    callback: ResultCallback[DocumentSnapshot],
    source: int | None = None,
) -> None

Read the document once.

Parameters:

Name Type Description Default
callback ResultCallback[DocumentSnapshot]

gets (DocumentSnapshot, None) or (None, error). A missing document is not an error: snapshot.exists is False.

required
source int | None

FIRFirestoreSource.Default (default) / Server / Cache.

None

add_snapshot_listener

add_snapshot_listener(
    callback: ResultCallback[DocumentSnapshot],
    include_metadata_changes: bool = False,
    options: SnapshotListenOptions | None = None,
) -> ListenerRegistration

Listen to the document: callback runs now, then on every change.

Parameters:

Name Type Description Default
callback ResultCallback[DocumentSnapshot]

gets (DocumentSnapshot, None) or (None, error). After an error, the listener stops.

required
include_metadata_changes bool

also call back on metadata-only changes.

False
options SnapshotListenOptions | None

SnapshotListenOptions; overrides include_metadata_changes.

None

Returns:

Type Description
ListenerRegistration

A ListenerRegistration. Call .remove() to stop listening.

DocumentSnapshot

DocumentSnapshot(snapshot: ObjCObject)

The data of one document, as read at one moment.

Values are plain Python (see to_python): timestamps are datetime, null is None, references are DocumentReference.

Snapshots come from callbacks; you do not make them yourself.

Parameters:

Name Type Description Default
snapshot ObjCObject

the native FIRDocumentSnapshot.

required

Methods:

Name Description
data_with_server_timestamp_behavior

All fields, choosing how pending server timestamps read.

get

One field's value.

Attributes:

Name Type Description
document_id str

The document's ID (the last part of its path).

exists bool

True if the document exists. When False, data is {}.

reference DocumentReference

The DocumentReference this snapshot was read from.

metadata SnapshotMetadata

Whether the data came from the cache, and has pending writes.

data dict[str, Any]

All fields as a dict. {} when the document does not exist.

document_id property

document_id: str

The document's ID (the last part of its path).

exists property

exists: bool

True if the document exists. When False, data is {}.

reference property

reference: DocumentReference

The DocumentReference this snapshot was read from.

metadata property

metadata: SnapshotMetadata

Whether the data came from the cache, and has pending writes.

data property

data: dict[str, Any]

All fields as a dict. {} when the document does not exist.

Pending server timestamps read as None; see data_with_server_timestamp_behavior.

data_with_server_timestamp_behavior

data_with_server_timestamp_behavior(
    behavior: int,
) -> dict[str, Any]

All fields, choosing how pending server timestamps read.

Parameters:

Name Type Description Default
behavior int

FIRServerTimestampBehavior.None_ / Estimate / Previous.

required

get

get(field: str) -> Any

One field's value.

::

snapshot.get("name")
snapshot.get("address.city")  # a nested field
snapshot["name"]              # the same as get("name")

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name for a nested field.

required

Returns:

Type Description
Any

The value as Python (see to_python), or None if the field (or

Any

the document) does not exist.

FIRAggregateSource

Where aggregate queries (count, sum, average) are calculated.

Attributes:

Name Type Description
Server Final

On the server. The only option the SDK offers.

Server class-attribute instance-attribute

Server: Final = 0

On the server. The only option the SDK offers.

FIRDocumentChangeType

The raw values behind DocumentChange.type.

FIRFirestoreSource

Where get_document / get_documents read from.

Attributes:

Name Type Description
Default Final

The server when online, else the cache.

Server Final

Only the server. Fails when offline.

Cache Final

Only the local cache. Fails if the data is not cached.

Default class-attribute instance-attribute

Default: Final = 0

The server when online, else the cache.

Server class-attribute instance-attribute

Server: Final = 1

Only the server. Fails when offline.

Cache class-attribute instance-attribute

Cache: Final = 2

Only the local cache. Fails if the data is not cached.

FIRListenSource

Where a snapshot listener gets its data.

Attributes:

Name Type Description
Default Final

The server and the cache.

Cache Final

Only the local cache.

Default class-attribute instance-attribute

Default: Final = 0

The server and the cache.

Cache class-attribute instance-attribute

Cache: Final = 1

Only the local cache.

FIRServerTimestampBehavior

What a server timestamp that is still pending reads as, before the server has set it.

Attributes:

Name Type Description
None_ Final

None (named None_ because None is a Python keyword).

Estimate Final

An estimate from the local clock.

Previous Final

The field's previous value.

None_ class-attribute instance-attribute

None_: Final = 0

None (named None_ because None is a Python keyword).

Estimate class-attribute instance-attribute

Estimate: Final = 1

An estimate from the local clock.

Previous class-attribute instance-attribute

Previous: Final = 2

The field's previous value.

FieldValue

Special values for set_data / update_data: the server applies them, instead of storing them as they are.

::

doc.update_data({"visits": FieldValue.field_value_for_integer_increment(1)})

Methods:

Name Description
field_value_for_delete

Delete the field (update_data, or set_data with merge).

field_value_for_server_timestamp

The time the server receives the write.

field_value_for_array_union

Add elements to an array field, skipping those already in it.

field_value_for_array_remove

Remove every instance of each element from an array field.

field_value_for_integer_increment

Add an integer to a number field, on the server.

field_value_for_double_increment

Add a float to a number field, on the server.

field_value_for_delete staticmethod

field_value_for_delete() -> ObjCObject

Delete the field (update_data, or set_data with merge).

field_value_for_server_timestamp staticmethod

field_value_for_server_timestamp() -> ObjCObject

The time the server receives the write.

field_value_for_array_union staticmethod

field_value_for_array_union(
    elements: Iterable[Any],
) -> ObjCObject

Add elements to an array field, skipping those already in it.

If the field is missing or not an array, it becomes an array of elements.

Parameters:

Name Type Description Default
elements Iterable[Any]

the elements to add. Converted with to_firestore.

required

Returns:

Type Description
ObjCObject

A sentinel to use as a field value in set_data / update_data.

field_value_for_array_remove staticmethod

field_value_for_array_remove(
    elements: Iterable[Any],
) -> ObjCObject

Remove every instance of each element from an array field.

Parameters:

Name Type Description Default
elements Iterable[Any]

the elements to remove. Converted with to_firestore.

required

Returns:

Type Description
ObjCObject

A sentinel to use as a field value in set_data / update_data.

field_value_for_integer_increment staticmethod

field_value_for_integer_increment(value: int) -> ObjCObject

Add an integer to a number field, on the server.

Safe when several devices increment at once. A missing field starts at 0.

Parameters:

Name Type Description Default
value int

the amount to add. Negative to subtract.

required

Returns:

Type Description
ObjCObject

A sentinel to use as a field value in set_data / update_data.

field_value_for_double_increment staticmethod

field_value_for_double_increment(
    value: float,
) -> ObjCObject

Add a float to a number field, on the server.

Safe when several devices increment at once. A missing field starts at 0.

Parameters:

Name Type Description Default
value float

the amount to add. Negative to subtract.

required

Returns:

Type Description
ObjCObject

A sentinel to use as a field value in set_data / update_data.

Filter

Filter(filter_: ObjCObject, _parts: tuple[Part, ...] = ())

A condition for Query.query_where_filter.

Filters can be combined with or_filter_with_filters and and_filter_with_filters, and nested::

Filter.or_filter_with_filters([
    Filter.filter_where_field_is_equal_to("capital", True),
    Filter.filter_where_field_is_greater_than("population", 1_000_000),
])

Make filters with the static methods; you do not call Filter(...) yourself.

Parameters:

Name Type Description Default
filter_ ObjCObject

the native FIRFilter.

required

Methods:

Name Description
filter_where_field_is_equal_to

Match documents where field == value.

filter_where_field_is_not_equal_to

Match documents where field != value.

filter_where_field_is_less_than

Match documents where field < value.

filter_where_field_is_less_than_or_equal_to

Match documents where field <= value.

filter_where_field_is_greater_than

Match documents where field > value.

filter_where_field_is_greater_than_or_equal_to

Match documents where field >= value.

filter_where_field_array_contains

Match documents whose array field contains value.

filter_where_field_array_contains_any

Match documents whose array field contains at least one of values.

filter_where_field_in

Match documents where field is equal to one of values.

filter_where_field_not_in

Match documents where field is none of values.

or_filter_with_filters

A filter that matches if ANY of filters matches.

and_filter_with_filters

A filter that matches if ALL of filters match.

filter_where_field_is_equal_to staticmethod

filter_where_field_is_equal_to(
    field: str, value: Any
) -> Filter

Match documents where field == value.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. None matches Firestore null. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_is_not_equal_to staticmethod

filter_where_field_is_not_equal_to(
    field: str, value: Any
) -> Filter

Match documents where field != value.

Documents that do not have field do not match.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_is_less_than staticmethod

filter_where_field_is_less_than(
    field: str, value: Any
) -> Filter

Match documents where field < value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_is_less_than_or_equal_to staticmethod

filter_where_field_is_less_than_or_equal_to(
    field: str, value: Any
) -> Filter

Match documents where field <= value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_is_greater_than staticmethod

filter_where_field_is_greater_than(
    field: str, value: Any
) -> Filter

Match documents where field > value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_is_greater_than_or_equal_to staticmethod

filter_where_field_is_greater_than_or_equal_to(
    field: str, value: Any
) -> Filter

Match documents where field >= value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_array_contains staticmethod

filter_where_field_array_contains(
    field: str, value: Any
) -> Filter

Match documents whose array field contains value.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the element to look for. Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

filter_where_field_array_contains_any staticmethod

filter_where_field_array_contains_any(
    field: str, values: Sequence[Any]
) -> Filter

Match documents whose array field contains at least one of values.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
values Sequence[Any]

the elements to look for (up to 30). Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

values is not a list or tuple, or holds a value Firestore cannot store.

ValueError

values is empty, or has more than 30 values (an empty list would abort the app in the SDK).

filter_where_field_in staticmethod

filter_where_field_in(
    field: str, values: Sequence[Any]
) -> Filter

Match documents where field is equal to one of values.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
values Sequence[Any]

the allowed values (up to 30). Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

values is not a list or tuple, or holds a value Firestore cannot store.

ValueError

values is empty, or has more than 30 values (an empty list would abort the app in the SDK).

filter_where_field_not_in staticmethod

filter_where_field_not_in(
    field: str, values: Sequence[Any]
) -> Filter

Match documents where field is none of values.

Documents that do not have field do not match.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
values Sequence[Any]

the values to exclude (up to 10). Converted with to_firestore.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

Raises:

Type Description
TypeError

values is not a list or tuple, or holds a value Firestore cannot store.

ValueError

values is empty, or has more than 10 values (an empty list would abort the app in the SDK).

or_filter_with_filters staticmethod

or_filter_with_filters(filters: Iterable[Filter]) -> Filter

A filter that matches if ANY of filters matches.

Parameters:

Name Type Description Default
filters Iterable[Filter]

the filters to combine. They can be combined filters too.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

and_filter_with_filters staticmethod

and_filter_with_filters(
    filters: Iterable[Filter],
) -> Filter

A filter that matches if ALL of filters match.

Parameters:

Name Type Description Default
filters Iterable[Filter]

the filters to combine. They can be combined filters too.

required

Returns:

Type Description
Filter

A Filter for Query.query_where_filter.

ListenerRegistration

ListenerRegistration(
    registration: ObjCObject, on_remove: Callable[[], None]
)

Given back by every add_snapshot_listener. Call remove() to stop.

A listener keeps using the network (and counts reads) until it is removed.

Parameters:

Name Type Description Default
registration ObjCObject

the native FIRListenerRegistration.

required
on_remove Callable[[], None]

called once, when the listener is removed (releases the listener's callback block).

required

Methods:

Name Description
remove

Stop the updates. Safe to call more than once.

remove

remove() -> None

Stop the updates. Safe to call more than once.

SnapshotListenOptions

SnapshotListenOptions(
    include_metadata_changes: bool = False,
    source: int | None = None,
)

Options for add_snapshot_listener(options=...).

Parameters:

Name Type Description Default
include_metadata_changes bool

also call back when only the metadata changes (for example has_pending_writes becoming False).

False
source int | None

FIRListenSource.Default or FIRListenSource.Cache.

None

Query

Query(ref: ObjCObject, _state: QueryState | None = None)

A query over a collection (or a collection group).

Every query_* method gives a NEW Query, so you can chain them::

db.collection_with_path("cities") \
    .query_where_field_is_equal_to("state", "CA") \
    .query_ordered_by_field("population", descending=True) \
    .query_limited_to(10) \
    .get_documents(on_cities)

Values are converted with to_firestore, so datetime and None work in filters and cursors.

Mistakes the SDK would abort the app on raise ValueError instead: two filters that cannot be combined (two not-in, not-in with in or !=...), a limit below 1, an order after a start or end point, more cursor values than ordered fields, a cursor document without an ordered field, and query_limited_to_last without an order.

You get queries from CollectionReference, Firestore and the query_* methods; you do not make them yourself.

Parameters:

Name Type Description Default
ref ObjCObject

the native FIRQuery.

required

Methods:

Name Description
query_starting_at_document

Start the results at document, including it.

query_starting_after_document

Start the results right after document, for the next page.

query_ending_at_document

End the results at document, including it.

query_ending_before_document

End the results right before document.

query_starting_at_values

Start the results at these order-by values, including them.

query_starting_after_values

Start the results right after these order-by values.

query_ending_at_values

End the results at these order-by values, including them.

query_ending_before_values

End the results right before these order-by values.

query_where_field_is_equal_to

Match documents where field == value.

query_where_field_is_not_equal_to

Match documents where field != value.

query_where_field_is_less_than

Match documents where field < value.

query_where_field_is_less_than_or_equal_to

Match documents where field <= value.

query_where_field_is_greater_than

Match documents where field > value.

query_where_field_is_greater_than_or_equal_to

Match documents where field >= value.

query_where_field_array_contains

Match documents whose array field contains value.

query_where_field_array_contains_any

Match documents whose array field contains at least one of values.

query_where_field_in

Match documents where field is equal to one of values.

query_where_field_not_in

Match documents where field is none of values.

query_where_filter

Filter with a Filter, for OR conditions and nested AND/OR.

query_limited_to

Return at most limit documents, from the start of the order.

query_limited_to_last

Return at most limit documents, from the end of the order.

query_ordered_by_field

Order the results by field.

aggregate

An aggregate query for several values in one request.

get_documents

Read the matching documents once.

add_snapshot_listener

Listen to the matching documents: callback runs now, then on

Attributes:

Name Type Description
count AggregateQuery

An aggregate query for the number of matching documents.

count property

An aggregate query for the number of matching documents.

query_starting_at_document

query_starting_at_document(
    document: DocumentSnapshot,
) -> Query

Start the results at document, including it.

The query needs a query_ordered_by_field; the cursor uses the document's values for those fields.

Parameters:

Name Type Description Default
document DocumentSnapshot

a DocumentSnapshot from a callback (for example snapshot[-1] of the previous page). A DocumentReference is not enough: the cursor needs the document's data.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

document is not a DocumentSnapshot.

ValueError

the document does not exist, or lacks a field the query orders by (or has a server timestamp not written yet in one).

query_starting_after_document

query_starting_after_document(
    document: DocumentSnapshot,
) -> Query

Start the results right after document, for the next page.

Parameters:

Name Type Description Default
document DocumentSnapshot

a DocumentSnapshot from a callback (for example snapshot[-1] of the previous page). A DocumentReference is not enough: the cursor needs the document's data.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

document is not a DocumentSnapshot.

ValueError

the document does not exist, or lacks a field the query orders by (or has a server timestamp not written yet in one).

query_ending_at_document

query_ending_at_document(
    document: DocumentSnapshot,
) -> Query

End the results at document, including it.

Parameters:

Name Type Description Default
document DocumentSnapshot

a DocumentSnapshot from a callback (for example snapshot[-1] of the previous page). A DocumentReference is not enough: the cursor needs the document's data.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

document is not a DocumentSnapshot.

ValueError

the document does not exist, or lacks a field the query orders by (or has a server timestamp not written yet in one).

query_ending_before_document

query_ending_before_document(
    document: DocumentSnapshot,
) -> Query

End the results right before document.

Parameters:

Name Type Description Default
document DocumentSnapshot

a DocumentSnapshot from a callback (for example snapshot[-1] of the previous page). A DocumentReference is not enough: the cursor needs the document's data.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

document is not a DocumentSnapshot.

ValueError

the document does not exist, or lacks a field the query orders by (or has a server timestamp not written yet in one).

query_starting_at_values

query_starting_at_values(values: Sequence[Any]) -> Query

Start the results at these order-by values, including them.

::

cities.query_ordered_by_field("population").query_starting_at_values([1_000_000])

Parameters:

Name Type Description Default
values Sequence[Any]

one value per query_ordered_by_field call, in the same order. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

more values than query_ordered_by_field calls.

query_starting_after_values

query_starting_after_values(values: Sequence[Any]) -> Query

Start the results right after these order-by values.

Parameters:

Name Type Description Default
values Sequence[Any]

one value per query_ordered_by_field call, in the same order. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

more values than query_ordered_by_field calls.

query_ending_at_values

query_ending_at_values(values: Sequence[Any]) -> Query

End the results at these order-by values, including them.

Parameters:

Name Type Description Default
values Sequence[Any]

one value per query_ordered_by_field call, in the same order. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

more values than query_ordered_by_field calls.

query_ending_before_values

query_ending_before_values(values: Sequence[Any]) -> Query

End the results right before these order-by values.

Parameters:

Name Type Description Default
values Sequence[Any]

one value per query_ordered_by_field call, in the same order. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

more values than query_ordered_by_field calls.

query_where_field_is_equal_to

query_where_field_is_equal_to(
    field: str, value: Any
) -> Query

Match documents where field == value.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. None matches Firestore null. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

query_where_field_is_not_equal_to

query_where_field_is_not_equal_to(
    field: str, value: Any
) -> Query

Match documents where field != value.

Documents that do not have field do not match.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

ValueError

the query has a filter this one cannot be combined with (see Query).

query_where_field_is_less_than

query_where_field_is_less_than(
    field: str, value: Any
) -> Query

Match documents where field < value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

query_where_field_is_less_than_or_equal_to

query_where_field_is_less_than_or_equal_to(
    field: str, value: Any
) -> Query

Match documents where field <= value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

query_where_field_is_greater_than

query_where_field_is_greater_than(
    field: str, value: Any
) -> Query

Match documents where field > value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

query_where_field_is_greater_than_or_equal_to

query_where_field_is_greater_than_or_equal_to(
    field: str, value: Any
) -> Query

Match documents where field >= value.

Values are compared by Firestore's type ordering, so datetime, numbers and strings each only match values of the same type.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the value to compare with. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

query_where_field_array_contains

query_where_field_array_contains(
    field: str, value: Any
) -> Query

Match documents whose array field contains value.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
value Any

the element to look for. Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

value holds a value Firestore cannot store.

query_where_field_array_contains_any

query_where_field_array_contains_any(
    field: str, values: Sequence[Any]
) -> Query

Match documents whose array field contains at least one of values.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
values Sequence[Any]

the elements to look for (up to 30). Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

values is not a list or tuple, or holds a value Firestore cannot store.

ValueError

values is empty, or has more than 30 values (an empty list would abort the app in the SDK).

ValueError

the query has a filter this one cannot be combined with (see Query).

query_where_field_in

query_where_field_in(
    field: str, values: Sequence[Any]
) -> Query

Match documents where field is equal to one of values.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
values Sequence[Any]

the allowed values (up to 30). Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

values is not a list or tuple, or holds a value Firestore cannot store.

ValueError

values is empty, or has more than 30 values (an empty list would abort the app in the SDK).

ValueError

the query has a filter this one cannot be combined with (see Query).

query_where_field_not_in

query_where_field_not_in(
    field: str, values: Sequence[Any]
) -> Query

Match documents where field is none of values.

Documents that do not have field do not match.

Parameters:

Name Type Description Default
field str

the field name. Use a dotted name ("address.city") for a nested field.

required
values Sequence[Any]

the values to exclude (up to 10). Converted with to_firestore.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
TypeError

values is not a list or tuple, or holds a value Firestore cannot store.

ValueError

values is empty, or has more than 10 values (an empty list would abort the app in the SDK).

ValueError

the query has a filter this one cannot be combined with (see Query).

query_where_filter

query_where_filter(filter_: Filter) -> Query

Filter with a Filter, for OR conditions and nested AND/OR.

Parameters:

Name Type Description Default
filter_ Filter

the filter, for example Filter.or_filter_with_filters([...]).

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

the query has a filter this one cannot be combined with (see Query).

query_limited_to

query_limited_to(limit: int) -> Query

Return at most limit documents, from the start of the order.

Parameters:

Name Type Description Default
limit int

the most documents to return. Must be positive.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

limit is below 1. (2,147,483,647 or more means no limit, as in the SDK.)

TypeError

limit is not an int.

query_limited_to_last

query_limited_to_last(limit: int) -> Query

Return at most limit documents, from the end of the order.

The query must have a query_ordered_by_field. Documents still come back in the query's order.

Parameters:

Name Type Description Default
limit int

the most documents to return. Must be positive.

required

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

limit is below 1. (2,147,483,647 or more means no limit, as in the SDK.)

TypeError

limit is not an int.

query_ordered_by_field

query_ordered_by_field(
    field: str, descending: bool = False
) -> Query

Order the results by field.

Call it more than once to order by several fields. Documents that do not have field are left out of the results.

Parameters:

Name Type Description Default
field str

the field name (dotted for a nested field).

required
descending bool

True for largest first; False (the default) for smallest first.

False

Returns:

Type Description
Query

A new Query; this one is unchanged.

Raises:

Type Description
ValueError

the query already has a start or an end point (order first).

aggregate

aggregate(
    fields: Iterable[AggregateField],
) -> AggregateQuery

An aggregate query for several values in one request.

::

query.aggregate([
    AggregateField.aggregate_field_for_count(),
    AggregateField.aggregate_field_for_sum_of_field("population"),
])

Parameters:

Name Type Description Default
fields Iterable[AggregateField]

the values to calculate.

required

Returns:

Type Description
AggregateQuery

An AggregateQuery. Run it with aggregation_with_source.

get_documents

get_documents(
    callback: ResultCallback[QuerySnapshot],
    source: int | None = None,
) -> None

Read the matching documents once.

Parameters:

Name Type Description Default
callback ResultCallback[QuerySnapshot]

gets (QuerySnapshot, None) or (None, error).

required
source int | None

FIRFirestoreSource.Default (default) / Server / Cache.

None

Raises:

Type Description
ValueError

the query has query_limited_to_last but no order.

add_snapshot_listener

add_snapshot_listener(
    callback: ResultCallback[QuerySnapshot],
    include_metadata_changes: bool = False,
    options: SnapshotListenOptions | None = None,
) -> ListenerRegistration

Listen to the matching documents: callback runs now, then on every change. Use snapshot.document_changes for only what changed.

Parameters:

Name Type Description Default
callback ResultCallback[QuerySnapshot]

gets (QuerySnapshot, None) or (None, error). After an error, the listener stops.

required
include_metadata_changes bool

also call back on metadata-only changes.

False
options SnapshotListenOptions | None

SnapshotListenOptions; overrides include_metadata_changes.

None

Returns:

Type Description
ListenerRegistration

A ListenerRegistration. Call .remove() to stop listening.

Raises:

Type Description
ValueError

the query has query_limited_to_last but no order.

QuerySnapshot

QuerySnapshot(snapshot: ObjCObject)

The result of a query. You can use it like a list of DocumentSnapshot::

for doc in snapshot: ...
len(snapshot), snapshot[0], snapshot[-1], snapshot[1:3]

Snapshots come from callbacks; you do not make them yourself.

Parameters:

Name Type Description Default
snapshot ObjCObject

the native FIRQuerySnapshot.

required

Methods:

Name Description
document_changes_with_include_metadata_changes

What changed since the previous snapshot, optionally with metadata-only changes.

Attributes:

Name Type Description
query Query

The query that made this snapshot.

metadata SnapshotMetadata

Whether the data came from the cache, and has pending writes.

is_empty bool

True if no documents matched.

count int

The number of documents. The same as len(snapshot).

documents list[DocumentSnapshot]

The documents, in query order.

document_changes list[DocumentChange]

What changed since the previous snapshot of a listener. For the

query property

query: Query

The query that made this snapshot.

metadata property

metadata: SnapshotMetadata

Whether the data came from the cache, and has pending writes.

is_empty property

is_empty: bool

True if no documents matched.

count property

count: int

The number of documents. The same as len(snapshot).

documents property

documents: list[DocumentSnapshot]

The documents, in query order.

document_changes property

document_changes: list[DocumentChange]

What changed since the previous snapshot of a listener. For the first snapshot (and for get_documents) every document is ADDED.

document_changes_with_include_metadata_changes

document_changes_with_include_metadata_changes(
    include_metadata_changes: bool,
) -> list[DocumentChange]

What changed since the previous snapshot, optionally with metadata-only changes.

Parameters:

Name Type Description Default
include_metadata_changes bool

True to also list documents whose only change is their metadata (for example a pending write the server has now confirmed). False gives the same as document_changes.

required

Returns:

Type Description
list[DocumentChange]

A list of DocumentChange.

SnapshotMetadata

SnapshotMetadata(metadata: ObjCObject)

Where a snapshot's data came from.

Parameters:

Name Type Description Default
metadata ObjCObject

the native FIRSnapshotMetadata.

required

Attributes:

Name Type Description
is_from_cache bool

True if the data came from the local cache, not the server.

has_pending_writes bool

True if the data has local writes that the server has not confirmed yet.

is_from_cache property

is_from_cache: bool

True if the data came from the local cache, not the server.

has_pending_writes property

has_pending_writes: bool

True if the data has local writes that the server has not confirmed yet.

Transaction

Transaction(transaction: ObjCObject, error_pointer: Any)

Given to your function inside Firestore.run_transaction.

Do all reads before any write. The write methods give back the transaction, so you can chain them.

Parameters:

Name Type Description Default
transaction ObjCObject

the native FIRTransaction.

required
error_pointer Any

where Firestore expects an error, as an NSError ** pointer.

required

Methods:

Name Description
get_document

Read a document inside the transaction.

set_data

Write a document, creating it if needed.

update_data

Change only the given fields of a document. The document must exist.

delete_document

Delete a document.

get_document

get_document(
    document_reference: DocumentReference,
) -> DocumentSnapshot

Read a document inside the transaction.

Reads must come before any write in the same transaction.

Parameters:

Name Type Description Default
document_reference DocumentReference

the document to read.

required

Returns:

Type Description
DocumentSnapshot

A DocumentSnapshot (exists is False for a missing document).

Raises:

Type Description
TransactionException

the read failed. Let it propagate: the transaction stops with Firestore's error.

set_data

set_data(
    data: FirestoreData,
    document_reference: DocumentReference,
    merge: bool = False,
) -> Transaction

Write a document, creating it if needed.

Parameters:

Name Type Description Default
data FirestoreData

the fields, as Python values (see to_firestore).

required
document_reference DocumentReference

the document to write.

required
merge bool

False replaces the whole document; True keeps the fields not in data.

False

Returns:

Type Description
Transaction

This transaction, for chaining.

Raises:

Type Description
TypeError

data holds a value Firestore cannot store.

update_data

update_data(
    data: FirestoreData,
    document_reference: DocumentReference,
) -> Transaction

Change only the given fields of a document. The document must exist.

Parameters:

Name Type Description Default
data FirestoreData

the fields, as Python values (see to_firestore). Dotted names change one nested field.

required
document_reference DocumentReference

the document to change.

required

Returns:

Type Description
Transaction

This transaction, for chaining.

Raises:

Type Description
TypeError

data holds a value Firestore cannot store.

delete_document

delete_document(
    document_reference: DocumentReference,
) -> Transaction

Delete a document.

Parameters:

Name Type Description Default
document_reference DocumentReference

the document to delete.

required

Returns:

Type Description
Transaction

This transaction, for chaining.

TransactionException

Bases: Exception

Raise inside a run_transaction function to stop the transaction. Its message becomes the callback's error.description. (Any other exception stops the transaction too.)

WriteBatch

WriteBatch(batch: ObjCObject)

Many writes saved together: all of them work, or none do.

Up to 500 writes. Use a batch only once. Every method except commit gives back the batch, so you can chain them::

db.batch().set_data({"a": 1}, doc_a).delete_document(doc_b).commit(on_done)

Get a batch with Firestore.batch().

Parameters:

Name Type Description Default
batch ObjCObject

the native FIRWriteBatch.

required

Methods:

Name Description
set_data

Write a document, creating it if needed.

set_data_merge_fields

Write only some fields of data to a document, keeping the others.

update_data

Change only the given fields of a document.

delete_document

Delete a document. Its sub collections are not deleted.

commit

Send all the writes.

set_data

set_data(
    data: FirestoreData,
    document: DocumentReference,
    merge: bool = False,
) -> WriteBatch

Write a document, creating it if needed.

Parameters:

Name Type Description Default
data FirestoreData

the fields, as Python values (see to_firestore).

required
document DocumentReference

the document to write.

required
merge bool

False replaces the whole document; True keeps the fields not in data.

False

Returns:

Type Description
WriteBatch

This batch, for chaining.

Raises:

Type Description
TypeError

data holds a value Firestore cannot store.

set_data_merge_fields

set_data_merge_fields(
    data: FirestoreData,
    document: DocumentReference,
    fields: Sequence[str],
) -> WriteBatch

Write only some fields of data to a document, keeping the others.

Parameters:

Name Type Description Default
data FirestoreData

the fields, as Python values (see to_firestore).

required
document DocumentReference

the document to write.

required
fields Sequence[str]

the field names to write (dotted for nested fields). Fields of data not listed here are ignored.

required

Returns:

Type Description
WriteBatch

This batch, for chaining.

Raises:

Type Description
TypeError

data holds a value Firestore cannot store.

update_data

update_data(
    data: FirestoreData, document: DocumentReference
) -> WriteBatch

Change only the given fields of a document.

The document must exist when the batch is committed, or the whole batch fails.

Parameters:

Name Type Description Default
data FirestoreData

the fields, as Python values (see to_firestore). Dotted names change one nested field.

required
document DocumentReference

the document to change.

required

Returns:

Type Description
WriteBatch

This batch, for chaining.

Raises:

Type Description
TypeError

data holds a value Firestore cannot store.

delete_document

delete_document(document: DocumentReference) -> WriteBatch

Delete a document. Its sub collections are not deleted.

Parameters:

Name Type Description Default
document DocumentReference

the document to delete. A missing document is not an error.

required

Returns:

Type Description
WriteBatch

This batch, for chaining.

commit

commit(callback: ErrorCallback | None = None) -> None

Send all the writes.

Parameters:

Name Type Description Default
callback ErrorCallback | None

gets None once all the writes are saved, or the error (then none of them is saved).

None