Query Firebase Firestore documents by the ID

2019-04-09 23:33发布

As I got from 'Cloud Firestore Data Model' guide "each document is identified by a name." Is it possible to query a collection by that document identifier (which is the name or ID)?

For example, documents in the collection "Things" have IDs: 0, 1, 2 etc.:

enter image description here

Is it possible to query documents which IDs are less than 100?

3条回答
够拽才男人
2楼-- · 2019-04-09 23:45

You can query by documentId using the special sentinel FieldPath.documentId(), e.g.:

const querySnap = collection.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.

查看更多
看我几分像从前
3楼-- · 2019-04-09 23:50

Yes you can query a document identified by an id like suggested in @Michael Lehenbaur's response.

I want to add as an aside that it is bad practice to have predictable sequential keys since they lend themselves to scalability issues. You should use randomly generated keys to avoid hotspots in the database. For reference, see the firebase mailing list discussion

查看更多
太酷不给撩
4楼-- · 2019-04-09 23:51

You can also try "filling" your ids so that '1' becomes '001', '2' becomes '002', and so on. If you have no idea your total number of items it may not seem convenient but it should make your query work.

查看更多
登录 后发表回答