0

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?

Samuel Hulla
  • 6,617
  • 7
  • 36
  • 70
FlutterFirebase
  • 2,163
  • 6
  • 28
  • 60
  • Firestore doesn't do timestamp ordering of documents by default. You have to add a timestamp field to each document, and use that in your queries. You will need at least two queries to get only these two documents. – Doug Stevenson Nov 16 '20 at 16:11

1 Answers1

1

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! :-)

Samuel Hulla
  • 6,617
  • 7
  • 36
  • 70
  • first, and last - and downloading every document in between. A rather expensive operation. The other answer queries *only* the two documents, and incurs the *read* cost of only two documents. – LeadDreamer Nov 16 '20 at 16:29
  • @LeadDreamer actually I'd be curious what's more performance heavy, accessing the docs or the two asynchronous calls on the two separate `orderBy` queries, though they have limit so I'd assume they are more performant. I'd be curious if internally the `limit` actually does something to the `CollectionReference` or just fetches and then then simply returns the first `QueryDocument` – Samuel Hulla Nov 17 '20 at 00:33
  • limit(1) **literally** only fetches one document, so costs 1 read. It only transports one document, so less bandwidth used. It only transports one document so it takes less time. All at the server. *IF*, for some reason, you were to *subsequently* *always* need the rest of the documents, then they would then be in cache, but I don't see a *performance* reason **NOT** to use .limit() – LeadDreamer Nov 17 '20 at 01:33