CollectionReference
Represents a reference to a collection in a database.
Path parts and field names must not contain forward slashes ( / ), and cannot start with underscores ( _ ) or dollar signs ($). Additionally, path parts cannot contain spaces. The total length of the document path cannot exceed 230 characters.
Attributes
Path
The path to this collection reference in the database.
Id
The collection ID of this collection reference (e.g. items in path players/uid123/items)
Parent
The parent document reference if any.
Methods
Document(string id)
Gets a reference to a document in this collection.
Parameters:
string id: The ID of the document in this collection.
Returns: DocumentReference : A reference to the specified document.
Example
var locationsRef = database.Collection("locations");
var locationARef = locationsRef.Document("a");Possible exceptions
ArgumentException
If the ID is invalid or contains slashes (which can cause injection attacks).
GetDocuments()
Gets all documents in this collection.
Returns: Task<Collection>: The collection with an array of documents.
Example
var locationsCollection = await locationsRef.GetDocuments();Possible exceptions
ForbiddenException
NoAccess
The database rules forbid read access to some of the documents in the collection.
NotFoundException
DatabaseNotFound
The database was not found.
QueryDocuments(DocumentQueryOperation[]? query = null,
string[]? includeFields = null,
string[]? excludeFields = null,
Dictionary<string, FieldSortDirection>? sort = null,
Dictionary<string, object>? startAfter = null,
int? limit = null)
Finds/projects/sorts documents in this collection.
Only either includeFields or excludeFields can be specified at a time.
sort must be provided and matching the fields of startAfter if startAfter is provided.
Parameters:
DocumentQueryOperation[]? query: The queries to filter documents by.string[]? includeFields: The fields to be retrieved in each document retrieved.string[]? excludeFields: The fields to be excluded in each document retrieved.Dictionary<string, FieldSortDirection>? sort: The sort specification for the documents.Dictionary<string, object>? startAfter: The field values to start after for sorted fields. Allows for pagination.int? limit: The maximum number of documents to retrieve at a time.
Returns: Task<Collection>: The collection with the array of filtered documents.
Example
var locationsCollection = await locationsRef.QueryDocuments(
new[]
{
DocumentQueryOperation.GreaterThan("points", 10),
DocumentQueryOperation.GeoNear("coordinates", myLocation, maxDistance: 100)
},
includeFields: new[] { "name", "points", "coordinates" },
sort: new Dictionary<string, FieldSortDirection>
{
{ "points", FieldSortDirection.Descending },
{ "name", FieldSortDirection.Ascending }
},
startAfter: new Dictionary<string, object>
{
{ "points", 15 },
{ "name", "A" }
},
limit: 10
);Possible exceptions
BadRequestException
InvalidProjectionKey
Certain fields, such as _id, cannot be used for projection.
ForbiddenException
NoAccess
The database rules forbid read access to some of the documents retrieved by the query.
NotFoundException
DatabaseNotFound
The database was not found.
ListenDocuments(Action<MultiDocumentChange> onData,
Action<Exception> onError
Action onClosed,
DocumentQueryOperation[]? query = null,
string[]? includeFields = null,
string[]? excludeFields = null,
Dictionary<string, FieldSortDirection>? sort = null,
bool autoReconnect = true,
bool sendInitialData = false)
Listens to changes in documents of a collection. Changes notified are document updates, inserts and deletes. Only either includeFields or excludeFields can be specified at a time.
Parameters:
Action<MultiDocumentChange> onData: The callback when an update is received.Action<Exception> onError: The callback when an error is received.Action onClosed: The callback when the connection is closed and will not be restored.DocumentQueryOperation[]? query: The queries to filter documents by.
string[]? includeFields: The fields to be retrieved in each document received.string[]? excludeFields: The fields to be excluded in each document received.Dictionary<string, FieldSortDirection>? sort: The sort specification for the documents (for initial data).bool autoReconnect: Whether to automatically reconnect to the server when the internet connection drops.bool sendInitialData: Whether to send all matching documents when the listener is first set up.
Returns: Func<Task>: A function to close the listener.
Example
locationsRef.ListenDocuments(
onData: change =>
{
switch (change.Type)
{
case MultiDocumentChangeType.Initial:
/* When initial data is received, only change.Documents is available. */
Debug.Log("Initial data received:");
foreach (var document in change.Documents)
{
Debug.Log($"Document ID: {document.Reference.Id}");
}
/* Handle the initial documents as needed */
break;
case MultiDocumentChangeType.Insert:
/* When an insert is received, change.Documents (with 1 element) is available. */
var insertedDocument = change.Documents[0];
Debug.Log($"Inserted document ID: {insertedDocument.Reference.Id}");
/* Handle the inserted document as needed */
break;
case MultiDocumentChangeType.Update:
/* When an update is received, change.ChangeDescription and change.Documents (with 1 element) is available. */
var updatedFields = change.ChangeDescription!.UpdatedFields;
foreach (var field in updatedFields)
{
Debug.Log($"Field updated: {field.Key} = {field.Value}");
/* Handle the updated field as needed */
}
var deletedFields = change.ChangeDescription!.DeletedFields;
foreach (var field in deletedFields)
{
Debug.Log($"Field deleted: {field}");
/* Handle the deleted field as needed */
}
var changedDocument = change.Documents[0];
Debug.Log($"Updated Document ID: {changedDocument.Reference.Id}");
/* Handle the updated document as needed */
break;
case MultiDocumentChangeType.Delete:
/* When a delete is received, only change.Documents (with 1 element) is available. */
var deletedDocument = change.Documents[0];
Debug.Log($"Deleted Document ID: {deletedDocument.Reference.Id}");
/* Handle the deleted document as needed */
break;
}
},
onError: error =>
{
Debug.LogError($"Error listening to documents: {error.Message}");
/* Handle the error as needed */
},
onClosed: () =>
{
Debug.Log("Listener closed");
/* Handle the listener being closed, e.g. by the game or due to network issues */
},
query: new[]
{
DocumentQueryOperation.GreaterThan("points", 10),
DocumentQueryOperation.GeoNear("coordinates", myLocation, maxDistance: 100)
},
includeFields: new[] { "name", "points", "coordinates" },
sort: new Dictionary<string, FieldSortDirection>
{
{ "points", FieldSortDirection.Descending },
{ "name", FieldSortDirection.Ascending }
},
autoReconnect: true,
sendInitialData: true
);Possible exceptions
BadRequestException
InvalidProjectionKey
Certain fields, such as _id, cannot be used for projection.
ForbiddenException
NoAccess
The database rules forbid read access to some of the retrieved documents.
NotFoundException
DatabaseNotFound
The database was not found.
SetDocuments(Dictionary<string, Dictionary<string, object>> documents)
Adds or replaces multiple documents to this collection. A maximum of 50 documents can be set at once.
Path parts and field names must not contain forward slashes ( / ), and cannot start with underscores ( _ ) or dollar signs ($). The total length of the document path cannot exceed 230 characters.
Parameters:
Dictionary<string, Dictionary<string, object>> documents: The documents to be set, with ID as key and data as value.
Example
var itemsRef = database.Collection("players").Document("player1").Collection("items");
await itemsRef.SetDocuments(new Dictionary<string, Dictionary<string, object>>
{
{
"item1", new Dictionary<string, object>
{
{ "id", "sword" },
{ "acquiredDate", "2025-06-27" }
}
},
{
"item2", new Dictionary<string, object>
{
{ "id", "shield" },
{ "acquiredDate", "2025-06-27" }
}
}
});Possible exceptions
ArgumentException: The maximum number of documents that can be set at once is 50.
BadRequestException
InvalidPath
The resolved path of the document is invalid.
InvalidDocumentData
One of the document data is invalid (e.g. ID or field name is invalid).
ForbiddenException
NoAccess
The database rules forbid add access to some of these documents.
NotFoundException
DatabaseNotFound
The database was not found.
UpdateDocuments(Dictionary<string, DocumentDataOperation> update,
DocumentQueryOperation[]? filter = null)
Updates matching documents in this collection.
Parameters:
Dictionary<string, DocumentDataOperation> update: The update specification, with field path as key and operation as value.DocumentQueryOperation[]? filter: The filters to find matching documents to update.
Example
var playerRef = database.Collection("players");
await playerRef.UpdateDocuments(
update: new Dictionary<string, DocumentDataOperation>
{
{ "skillLevel", DocumentDataOperation.Inc(10) },
{ "matchesPlayed", DocumentDataOperation.Inc(1) }
},
filter: new[]
{
DocumentQueryOperation.In("playerId", new[] { "player123", "player456" })
}
);Possible exceptions
BadRequestException
InvalidField
The field path of a field being updated is invalid (e.g. accessing a field in a primitive).
You cannot rename fields in an array-embedded dictionary (e.g. renaming mylist.0.age to age)
InvalidUpdateDataType
The data type of the field being updated does not match the update operation (e.g. Inc operation on a field with a string value)
ForbiddenException
NoAccess
The database rules forbid update access to some of these documents.
NotFoundException
DatabaseNotFound
The database was not found.
DeleteDocuments(DocumentQueryOperation[]? filter = null)
Deletes matching documents from this collection.
Parameters:
DocumentQueryOperation[]? filter: The filters to find matching documents to delete.
Example
var itemsRef = database.Collection("players").Document("player123").Collection("items");
await itemsRef.DeleteDocuments(new []
{
DocumentQueryOperation.Equal("type", "weapon"),
DocumentQueryOperation.LessThan("level", 5)
});Possible exceptions
ForbiddenException
NoAccess
The database rules forbid delete access to some of these documents.
NotFoundException
DatabaseNotFound
The database was not found.
Last updated