Query

Query

new Query()

A Query refers to a query which you can read or stream from. You can also construct refined Query objects by adding filters and ordering.

Members

firestore

The Firestore instance for the Firestore database (useful for performing transactions, etc.).

Example
```
let collectionRef = firestore.collection('col');

collectionRef.add({foo: 'bar'}).then(documentReference => {
  let firestore = documentReference.firestore;
  console.log(`Root location for document is ${firestore.formattedName}`);
});
```

Methods

aggregate(aggregateSpec)

Returns a query that can perform the given aggregations.

The returned query, when executed, calculates the specified aggregations over the documents in the result set of this query without actually downloading the documents.

Using the returned query to perform aggregations is efficient because only the final aggregation values, not the documents' data, is downloaded. The returned query can perform aggregations of the documents count the documents in cases where the result set is prohibitively large to download entirely (thousands of documents).

Parameters:
Name Type Description
aggregateSpec

An AggregateSpec object that specifies the aggregates to perform over the result set. The AggregateSpec specifies aliases for each aggregate, which can be used to retrieve the aggregate result.

Example
```typescript
const aggregateQuery = col.aggregate(query, {
  countOfDocs: count(),
  totalHours: sum('hours'),
  averageScore: average('score')
});

const aggregateSnapshot = await aggregateQuery.get();
const countOfDocs: number = aggregateSnapshot.data().countOfDocs;
const totalHours: number = aggregateSnapshot.data().totalHours;
const averageScore: number | null = aggregateSnapshot.data().averageScore;
```

count()

Returns a query that counts the documents in the result set of this query.

The returned query, when executed, counts the documents in the result set of this query without actually downloading the documents.

Using the returned query to count the documents is efficient because only the final count, not the documents' data, is downloaded. The returned query can count the documents in cases where the result set is prohibitively large to download entirely (thousands of documents).

Returns:
Type Description

a query that counts the documents in the result set of this query. The count can be retrieved from snapshot.data().count, where snapshot is the AggregateQuerySnapshot resulting from running the returned query.

endAt(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that ends at the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should end at or the field values to end this query at, in order of the query's order by.

Returns:
Type Description
Query

A query with the new ending point.

Example
```
let query = firestore.collection('col');

query.orderBy('foo').endAt(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

endBefore(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that ends before the set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should end before or the field values to end this query before, in order of the query's order by.

Returns:
Type Description
Query

A query with the new ending point.

Example
```
let query = firestore.collection('col');

query.orderBy('foo').endBefore(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

(async) explain()

Plans and optionally executes this query. Returns a Promise that will be resolved with the planner information, statistics from the query execution (if any), and the query results (if any).

Returns:
Type Description

A Promise that will be resolved with the planner information, statistics from the query execution (if any), and the query results (if any).

explainStream()

Executes the query and streams the results as the following object: {document?: DocumentSnapshot, metrics?: ExplainMetrics}

The stream surfaces documents one at a time as they are received from the server, and at the end, it will surface the metrics associated with executing the query.

Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

let count = 0;

query.explainStream({analyze: true}).on('data', (data) => {
  if (data.document) {
    // Use data.document which is a DocumentSnapshot instance.
    console.log(`Found document with name '${data.document.id}'`);
    ++count;
  }
  if (data.metrics) {
    // Use data.metrics which is an ExplainMetrics instance.
  }
}).on('end', () => {
  console.log(`Received ${count} documents.`);
});
```

(async) get() → {Promise.<QuerySnapshot>}

Executes the query and returns the results as a QuerySnapshot.

Returns:
Type Description
Promise.<QuerySnapshot>

A Promise that resolves with the results of the Query.

Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

query.get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

getInequalityFilterFields()

Returns the sorted array of inequality filter fields used in this query.

Returns:
Type Description

An array of inequality filter fields sorted lexicographically by FieldPath.

isEqual(other) → {boolean}

Returns true if this Query is equal to the provided value.

Parameters:
Name Type Description
other *

The value to compare against.

Returns:
Type Description
boolean

true if this Query is equal to the provided value.

limit(limit) → {Query}

Creates and returns a new Query that only returns the first matching documents.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the limit.

Parameters:
Name Type Description
limit number

The maximum number of items to return.

Returns:
Type Description
Query

The created Query.

Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.limit(1).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

limitToLast(limit)

Creates and returns a new Query that only returns the last matching documents.

You must specify at least one orderBy clause for limitToLast queries, otherwise an exception will be thrown during execution.

Results for limitToLast queries cannot be streamed via the stream() API.

Parameters:
Name Type Description
limit

The maximum number of items to return.

Returns:
Type Description

The created Query.

Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.limitToLast(1).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Last matching document is ${documentSnapshot.ref.path}`);
  });
});
```

offset(offset) → {Query}

Specifies the offset of the returned results.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the offset.

Parameters:
Name Type Description
offset number

The offset to apply to the Query results

Returns:
Type Description
Query

The created Query.

Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.limit(10).offset(20).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

onSnapshot(onNext, onErroropt) → {function}

Attaches a listener for QuerySnapshot events.

Parameters:
Name Type Attributes Description
onNext querySnapshotCallback

A callback to be called every time a new QuerySnapshot is available.

onError errorCallback <optional>

A callback to be called if the listen fails or is cancelled. No further callbacks will occur.

Returns:
Type Description
function

An unsubscribe function that can be called to cancel the snapshot listener.

Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

let unsubscribe = query.onSnapshot(querySnapshot => {
  console.log(`Received query snapshot of size ${querySnapshot.size}`);
}, err => {
  console.log(`Encountered error: ${err}`);
});

// Remove this listener.
unsubscribe();
```

orderBy(fieldPath, directionStropt) → {Query}

Creates and returns a new Query that's additionally sorted by the specified field, optionally in descending order instead of ascending.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the field mask.

Parameters:
Name Type Attributes Description
fieldPath string | FieldPath

The field to sort by.

directionStr string <optional>

Optional direction to sort by ('asc' or 'desc'). If not specified, order will be ascending.

Returns:
Type Description
Query

The created Query.

Example
```
let query = firestore.collection('col').where('foo', '>', 42);

query.orderBy('foo', 'desc').get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

select(…fieldPaths) → {Query}

Creates and returns a new Query instance that applies a field mask to the result and returns only the specified subset of fields. You can specify a list of field paths to return, or use an empty list to only return the references of matching documents.

Queries that contain field masks cannot be listened to via onSnapshot() listeners.

This function returns a new (immutable) instance of the Query (rather than modify the existing instance) to impose the field mask.

Parameters:
Name Type Attributes Description
fieldPaths string | FieldPath <repeatable>

The field paths to return.

Returns:
Type Description
Query

The created Query.

Example
```
let collectionRef = firestore.collection('col');
let documentRef = collectionRef.doc('doc');

return documentRef.set({x:10, y:5}).then(() => {
  return collectionRef.where('x', '>', 5).select('y').get();
}).then((res) => {
  console.log(`y is ${res.docs[0].get('y')}.`);
});
```

startAfter(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that starts after the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should start after or the field values to start this query after, in order of the query's order by.

Returns:
Type Description
Query

A query with the new starting point.

Example
```
let query = firestore.collection('col');

query.orderBy('foo').startAfter(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

startAt(…fieldValuesOrDocumentSnapshot) → {Query}

Creates and returns a new Query that starts at the provided set of field values relative to the order of the query. The order of the provided values must match the order of the order by clauses of the query.

Parameters:
Name Type Attributes Description
fieldValuesOrDocumentSnapshot * | DocumentSnapshot <repeatable>

The snapshot of the document the query results should start at or the field values to start this query at, in order of the query's order by.

Returns:
Type Description
Query

A query with the new starting point.

Example
```
let query = firestore.collection('col');

query.orderBy('foo').startAt(42).get().then(querySnapshot => {
  querySnapshot.forEach(documentSnapshot => {
    console.log(`Found document at ${documentSnapshot.ref.path}`);
  });
});
```

stream() → {Stream.<QueryDocumentSnapshot>}

Executes the query and streams the results as QueryDocumentSnapshots.

Returns:
Type Description
Stream.<QueryDocumentSnapshot>

A stream of QueryDocumentSnapshots.

Example
```
let query = firestore.collection('col').where('foo', '==', 'bar');

let count = 0;

query.stream().on('data', (documentSnapshot) => {
  console.log(`Found document with name '${documentSnapshot.id}'`);
  ++count;
}).on('end', () => {
  console.log(`Total count is ${count}`);
});
```

withConverter(converter)

Applies a custom data converter to this Query, allowing you to use your own custom model objects with Firestore. When you call get() on the returned Query, the provided converter will convert between Firestore data of type NewDbModelType and your custom type NewAppModelType.

Using the converter allows you to specify generic type arguments when storing and retrieving objects from Firestore.

Passing in null as the converter parameter removes the current converter.

Parameters:
Name Type Description
converter FirestoreDataConverter | null

Converts objects to and from Firestore. Passing in null removes the current converter.

Returns:
Type Description

A Query that uses the provided converter.

Example
```
class Post {
  constructor(readonly title: string, readonly author: string) {}

  toString(): string {
    return this.title + ', by ' + this.author;
  }
}

const postConverter = {
  toFirestore(post: Post): FirebaseFirestore.DocumentData {
    return {title: post.title, author: post.author};
  },
  fromFirestore(
    snapshot: FirebaseFirestore.QueryDocumentSnapshot
  ): Post {
    const data = snapshot.data();
    return new Post(data.title, data.author);
  }
};

const postSnap = await Firestore()
  .collection('posts')
  .withConverter(postConverter)
  .doc().get();
const post = postSnap.data();
if (post !== undefined) {
  post.title; // string
  post.toString(); // Should be defined
  post.someNonExistentProperty; // TS error
}

```