7

I am using the new Cloud Firestore in Android. So I am facing this issue in firestore. I want to query a document, which contains an id in their array fields.

for example, I have a document with a field in firestore containing an array of integers like this: image1

So when I have an id 66940, I can get the document and other documents which contains the id, without returning other documents which don't contain the id 66940.


Other than this approach, I can also use the id (66940) to search it in the document id. My documents id format is like this:
- 66940_88123
- 12323_66940

The idea is, to return documents which contain 66940 in their ID. I've read about a solution here, but I don't really understand how to implement it.

Ferry Tan
  • 218
  • 2
  • 10

1 Answers1

7

This is a common question, so we have posted some documentation on how to work with arrays in Cloud Firestore: https://firebase.google.com/docs/firestore/solutions/arrays

In short, if you want to query for array membership it's better to store your data as a map of booleans.

So instead of this:

{
  name: "sam",
  userGgIds: [12345, 67890]
}

You want this:

{
  name: "sam",
  userGgIds: {
    12345: true,
    67890: true
  }
}

Then you can do this query to search for documents that contain the ID "12345"

db.collection("users").where("userGgIds.12345", "==", true).get()
Sam Stern
  • 24,624
  • 13
  • 93
  • 124
  • 1
    Ah of course! I wish I had made the connection to inter-document references. Because of their importance and commonality it'd be great to reiterate in the docs that this would be the recommended use case for membership relationships (1:*, *:*). Time to do some rotations :| – yo.ian.g Nov 08 '17 at 18:44