skip to Main Content

I’m working on cloud firestore and let’s assume this is how my documents are structured in a collection:

{
    'name': 'something'
    'age': 23,
}

And I’ve some 200-300 users, and I’m storing their data like this. Now let’s say that I had to add a new field favorite_color. So I added it to all the new user accounts that are being created right now. So now some documents look like as follows:

{
        'name': 'something'
        'age': 23,
        'favorite_color': 'red',
}

Now I wanted to fetch these documents with the following query:
Get all docs where favorite_color is empty string or if the field just doesn't exist. I’ve no idea how to get this done. Can this even be done? Any help will be appreciated.

2

Answers


  1. I’m not sure how would this work with query but you can try the following code:

    Future<List<Map<String, dynamic>>> getData() async {
                try {
                  final list =
                      await FirebaseFirestore.instance.collection("users").get();
    
                  /// Result List
                  final List<Map<String, dynamic>> res = [];
    
                  for (final element in list.docs) {
                    final data = element.data();
    
                    if (data.containsKey("fieldName")) {
                      if ((data['fieldName'] as String).isEmpty) {
                        /// if Field is Empty
                        /// add to result list
                        res.add(data);
                      } else {
                        /// Handle Data with non empty fieldName
                      }
                    } else {
                      /// if Field is not present
                      /// add to result list
                      res.add(data);
                    }
                  }
    
                  return res;
                } catch (e) {
                  print(e.toString());
                  rethrow;
                }
              }
    
    Login or Signup to reply.
  2. Get all docs where favorite_color is empty string or if the field just
    doesn’t exist.

    These are two different cases.

    Let’s first start with querying for all documents for which the favorite_color field doesn’t exist: This is actually not possible with Firestore. The query mechanism is based on indexes and it is not possible to index a field that does not exist.

    Then, for the other case, i.e. querying for all documents for which the favorite_color field is an empty string, you can use the following Query:

    final stateQuery = collectionRef.where("favorite_color", isEqualTo: "");
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search