简体   繁体   中英

How to search for multiple values within a field of Firebase Cloud documents?

So I'm trying to make a favourites page in my android mobile application. The products are in their own top-level collection and structured as:

{
"Trainers": {
    "trainer1": {
        "brand": "Nike",
        "name": "Air Force 1",
        "colour": "Black"
        "url": ".................."   //FOR IMAGES

    },
    "trainer2": {
        "brand": "Adidas",
        "name": "Yeezy Boost 700",
        "colour": "Black"
        "url": ".................."   
    },
    "trainer3": {
        "brand": "Nike",
        "name": "Air Spiridons",
        "colour": "Cream"
        "url": ".................."   
    }
  }  
 }

I was then going to have another top-level collection that contains documents named as a users id, followed by an array of their favourite trainers 'name'. However, in order to populate the favourites page, I would then need to search the 'Trainer' collection for each shoe in a users favourites document.

So going back to my question, if User1 has liked 'Air Force 1 & Yeezy Boost 700' (or maybe more products than this) is it possible to query a collection where the documents 'name' field equals multiple values or is there a better way to structure a favourites activity?

is it possible to query a collection where the documents 'name' field equals multiple values or is there a better way to structure a favourites activity?

Sure it is, using an array that can contain max 10 values. According to the docs:

Similarly, use the array-contains-any operator to combine up to 10 array-contains clauses on the same field with a logical OR .

So in your case, you should use the following query:

usersRef.whereArrayContainsAny("name", Arrays.asList("Air Force 1", "Yeezy Boost 700"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM