Firestore: How to query data from a map of an array

11,053

Solution 1

You currently can't build a query that looks for an object field within an array. The only things you can find in an array are the entire contents of an array element, not a part of an element.

With NoSQL type databases, the usual practice is to structure you data in a way that suits your queries. So, in your case, you're going to have to structure you data to let you find documents where an array item contains a certain string. So, you could create another array that contains just the strings you want to query for. You will have make sure to keep these arrays up to date.

You could also reconsider the use of an array here. Arrays are good for positional data, but unless these contacts need to be stored in a certain order, you might want to instead store an object whose keys are the id, and whose field data also contains the id and name.

Solution 2

As Doug said, you can't query it, but, if you could structure your data to something that looks like this

  1. Store your data as a map
  2. Use id as key and name as value
  3. Now you can write a query that can get all the documents where contacts have id=1
db.collection("test").where("contacts.1", ">=", "").get()

Solution 3

If you have an array of maps or objects and want to get the docoments that contains this specific map/object like this ? array_of_maps.png

you can use

queryForCategory(categName: string, categAlias: string): Observable[] {
    firestore.collection('<Collection name>', ref =>

        ref.where('categories',
          "array-contains", {
            "alias": categAlias,
            "title": categName
          }
Share:
11,053
john
Author by

john

Updated on June 24, 2022

Comments

  • john
    john about 2 years

    Here is the schema for test db: enter image description here

    I want to write a query that can get all the documents where contacts have id=1 in any of the array index.

    I have checked array_contains operator for firestore but the thing is my array have map which then have field id.

    Thanks

  • Jbbae
    Jbbae over 5 years
    Thanks @Doug Stevenson - exactly what I was looking for. To clarify - it's not possible to query based on the keys of a map, right? (i.e. Only way is to create a separate array of only these keys)
  • Doug Stevenson
    Doug Stevenson over 5 years
    Or a separate object where the keys map to something like true/false.
  • Scott Fister
    Scott Fister about 4 years
    @DougStevenson out of interest, considering you still cannot query based on the keys of a map, what is the benefit of converting this to one? Either way you need the additional array of ids kept in sync. Unless of course you can foresee needing constant time lookup.