Can i search a Firestore DocumentID with a List<String>?

I am trying to search through my collection with some selection of documentID in a List. The List will consist of few String. Can I search through the Firestore collection using this?

This is the List:

 List<String> _selectedBusStop = List<String>();

This is the code I used in finding the DocumentID based on the list that is in here.

  Future <void> saveRoute(_selectedBusStop) async{
    Firestore.instance.collection('markers').where('BusstopName', isEqualTo: _selectedBusStop)
        .snapshots().listen((location) {
      if(location.documents.isNotEmpty){
        for (int i = 0; i < location.documents.length; i++){
          initRoute(location.documents[i].data, location.documents[i]);
        }
      }
    });
    setState(() {
    });
  }

I am using where and isEqualTo or is this approach wrong? Any idea how to make it work for this part? Thank you in advance for your help.

Update: This is how my Firestore looks like: Firestore

The List have some of the BusstopName but not all of it. I do not want to retrieve all the data from the Firestore just the one that is in the List. Sorry for causing so many misunderstanding.


Solution 1: Huthaifa Muayyad

Use the whereIn operator, like this:

   Future <void> saveRoute(_selectedBusStop) async{
    Firestore.instance.collection('markers').where('BusstopName', whereIn: _selectedBusStop)
        .snapshots().listen((location) {
      if(location.documents.isNotEmpty){
        for (int i = 0; i < location.documents.length; i++){
          initRoute(location.documents[i].data, location.documents[i]);
        }
      }
    });
    setState(() {
    });
  }


Solution 2: dcts

Assuming your documents have a unique id stored in the field BusstopName and also the documents actual id matches the content of this field, you have 2 possibilities.

(1) .where query

  • query data with collection("markers").where("BusstopName", "=", "yourBuststopId").
  • this returns a querySnapshot Object, on which you can call .size to check if there were any documents with that Id found (could be more than 1 if you have an inconsistent database).

(2) .doc query

  • query data with collection("markers").doc("yourBuststopId")
  • this returns a documentSnapshot Object, on which you can call .exist to check if the document actually exsists.

In both cases you need to do 1 query per Id, because Firestore queries only support equality and range operations. See this similar SO question. I would suggest to do the queries asynchronously, otherwise the time to execute will increase with the size of the array.

If you are concerned about costs, you only get billed for the results that actually return documents that exist.


Solution 3: dcts

you might also try this:

FirebaseFirestore.instance
  .collection('markers')
  .where('BusstopName', arrayContainsAny: ['Utar Bus Stop', 'Garden Bus Stop'])
  .get()
  .then(...);

Taken from the examples documentation