How can I check if a document contains a value inside a Firestore array?

147

If you just need to check if an array contains a specific value, then you can use arrayContains as shown below:

FirebaseFirestore.instance
  .collection('grupos')
  .where('miembros', arrayContains: 'ValueToCheck')
  .get()
  .then(...);

However, you can use arrayUnion() instead that will add the value if it's missing else it won't:

Firestore.instance
  .collection('grupos')
  .document('grupoId4')
  .updateData({ 'array':FieldValue.arrayUnion('ValueToAddInArray') });
Share:
147
RiseHit
Author by

RiseHit

Updated on January 04, 2023

Comments

  • RiseHit
    RiseHit over 1 year

    I'm using Flutter and Firestore , where is this database I'm trying to be able to see if a value exists inside an array, but I only found solutions that didn't work for me, sometimes they were in another language, but I want to be able to see if a value exists inside an array in a document.

    for example, I want to check if the user id userID1 is inside the array miembros marked in red in the following image

    example image of the array

    the idea is that I can do an if to add the value userID1 if it doesn't exist in the miembros array. actually thank you very much for any help

  • RiseHit
    RiseHit about 2 years
    Thank you very much for answering, I understand what you are saying, but in the first code, how could I search within a document? to avoid searching the entire collection
  • Dharmaraj
    Dharmaraj about 2 years
    @RiseHit so you know the document ID? In that case, you'll have to fetch the document and then check if value exists in the array yourself. arrayContains works in queries only.
  • RiseHit
    RiseHit about 2 years
    yes, in this case I know the Document ID, so I want to check if the user ID is already contained in the document array, that's what I'm looking to do, do you know more or less how I should do it? Would it be to obtain the snapshots and then in members look for the value if it exists?
  • Dharmaraj
    Dharmaraj about 2 years
    @RiseHit yes, you would have to fetch the document by ID, and then check the members array yourself using Dart.