2

In Firestore, I have a collection containing documents identified by timestamp: /records/timestamp
I would like to filter documents based on the id, using the javascript client API.
How can I write the query?
I am looking for something along the following line, but I cannot find the proper field name for id:

const query = firestore.collection(`/records`).where("id", "<", 1600766222);
Louis Coulet
  • 3,663
  • 1
  • 21
  • 39
  • I would recommend saving the timestamp as a field as you would be able to order it and also store it as a number. But if you really need the string ID for other purposes, us FieldPath.documentId(). – Siddharth Agrawal Sep 22 '20 at 10:44
  • Thank you for your comment. When you mention ordering, don't you think it is possible to do ```query.orderBy(FieldPath.documentId())``` ? – Louis Coulet Sep 22 '20 at 11:57
  • Yes Louis but this will order it the way strings are ordered. I suppose you'll want to arrange according to the order they came and not the order of their string values (ASCII VALUES). And in the future when you have a lot of data, you may want to add a new feature which uses timestamps as a number and it will be a headache to fix then – Siddharth Agrawal Sep 23 '20 at 06:22

1 Answers1

8

This is possible using FieldPath.documentId(), but there are limitations.

db.collection('CollectionName').where(firebase.firestore.FieldPath.documentId(), '<', '100').get()

But be aware that document IDs are strings and therefore this will include documents with ID '0' or '1', but not '2' since '2' > '100' lexicographically.

So if you want a numeric query, you'll need to write the document ID as a numeric field in the document and then do a normal query on it.

Reference: https://stackoverflow.com/a/48467056/1212903

Codex
  • 1,153
  • 1
  • 20
  • 31
  • Perfect! I will stick to using the document id instead of a field because I am fine with lexicographical ordering as I deal with timestamps exclusively. Would you do otherwise? – Louis Coulet Sep 22 '20 at 11:54