How can I check if a document contains a value inside a Firestore array?
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') });
RiseHit
Updated on January 04, 2023Comments
-
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 arraymiembros
marked in red in the following imagethe idea is that I can do an
if
to add the valueuserID1
if it doesn't exist in themiembros
array. actually thank you very much for any help -
RiseHit about 2 yearsThank 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 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 about 2 yearsyes, 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 about 2 years@RiseHit yes, you would have to fetch the document by ID, and then check the members array yourself using Dart.