FlutterFirebase
FlutterFirebase

Reputation: 2343

How to get first and last document in collection?

I have 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

Answers (1)

Samuel Hulla
Samuel Hulla

Reputation: 7089

I'm not sure by which Timestamp you want to sort, so I'm gonna assume your doc 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

Related Questions