Firestore: use "array-contains" query while ignoring specific Object attribute

Viewed 106

I have a collection where each document has a field which is an array and contains objects where each object is like {key: 0, value: "Some Value"}. Is there an option to do a comparison like array-contains, except while ignoring the key attribute? like finding all Documents with Arrays that contain an Object whose Value attribute equals to some value?

Thanks

1 Answers

The array-contains operation searches for an exact, complete match. It cannot check on just a subset of the information in the array.

The common workaround is to change your data model to allow the use-case, here by adding another array that contains just the information you have available. For example, if you have an array with some profile information for each user, but also want to be able to query for just their username, you'd end up with two array fields:

users: [
   { name: "AstroPrussia", url: "https://stackoverflow.com/users/5460401" },
   { name: "puf", url: "https://stackoverflow.com/users/209103" }
],
usernames: [
  "AstroPrussia",
  "puf"
]

Now if you want to search on the entire profile, you'd perform then array-contains on the users field. But if you only have the user's name, you'd perform an array-contains on the usernames field.

Related