beginner
beginner

Reputation: 2508

Android Firestore How to use document id as field in various queries

On this page Query firestore database for document id

I found this javascript example to use documentId in where clause

db.collection('books').where(firebase.firestore.FieldPath.documentId(), '==', 'fK3ddutEpD2qQqRMXNW5').get()

what would be the Android equivalent to that? I tried using

whereEqualTo(firebase.firestore.FieldPath.documentId(), 'fK3ddutEpD2qQqRMXNW5');

but it didn't work

Edit: I don't want to use

db.collection('books').document("fK3ddutEpD2qQqRMXNW5").get()

because I want to learn how to use documentId as field so that I can use that in other queries like

.orderBy(firebase.firestore.FieldPath.documentId())

(from Get data ordered by document Id in Firestore by Javascript?) in Android

In short, what is the equivalent of firebase.firestore.FieldPath.documentId() in Android?

Upvotes: 0

Views: 1469

Answers (3)

Alex Mamo
Alex Mamo

Reputation: 138834

If you don't want to use:

db.collection('books').document("fK3ddutEpD2qQqRMXNW5").get()

An option that you have is to add the document ID as a property of the document and use the following query:

db.collection("books").whereEqualTo("documentId", "fK3ddutEpD2qQqRMXNW5").get()

According to Doug Stevenson's comment, it turns out that:

db.collection("books").whereEqualTo(FieldPath.documentId(), "fK3ddutEpD2qQqRMXNW5").get()

Actually works, returning the same result as in case of:

db.collection('books').document("fK3ddutEpD2qQqRMXNW5").get()

Or:

db.collection("books").whereEqualTo("documentId", "fK3ddutEpD2qQqRMXNW5").get()

Now, you should simply attach a listener and you're done.

Upvotes: 2

Doug Stevenson
Doug Stevenson

Reputation: 317532

What you're showing should actually work. As you can see from the API documentation for FieldPath.documentId():

Returns A special sentinel FieldPath to refer to the ID of a document. It can be used in queries to sort or filter by the document ID.

So you should be able to use it to filter for document ID. I was able to perform a query like this with no problem. If it doesn't work for you, then something else is wrong - perhaps the document you asked for doesn't actually exist, or you are providing the wrong collection and ID.

Note that filtering by document ID like this doesn't work for collection group queries. For that, you do need to add the document ID as a field to filter.

Upvotes: 3

Sid Shinde
Sid Shinde

Reputation: 238

Instead of querying the collection for document id, query the document directly

db.collection('books').document("fK3ddutEpD2qQqRMXNW5").get()

Sometimes we miss the straight forward ones!

Upvotes: 1

Related Questions