Reputation: 2343
I have google-cloud-firestore collection with many documents.
I want to get first and last document in collection (sorted by timestamp).
How can I query for this?
Upvotes: 0
Views: 1621
Reputation: 7089
I'm not sure by which
Timestamp
you want to sort, so I'm gonna assume yourdoc
looks something like this/id/: { timestamp: FirebaseFirestore.Timestamp // ... whatever other properties }
You can get a Query
by querying on a CollectionReference<T>
via the .orderBy
method.
const collectionQuery = firestore
.collection('collectionName')
.orderBy('timestamp', 'asc')
Now we want to get a QuerySnapshot
(which will allow us to access the documents), by using the .get()
method.
const collectionSnapshot = await collectionQuery.get()
Now we just access the first and the last document.
const firstDocument = collectionSnapshot.isEmpty
? null
: collectionSnapshot.docs[0]
const lastDocument = collectionSnapshot.isEmpty
? null
: collectionSnapshot.docs[collectionSnapshot.docs.length - 1]
And voila, you have your first and last document! :-)
Upvotes: 1