Reputation: 327
I have a collection of users. Each user has an array named favoriteNames
.
root <- [Firestore]
users <- [Collection]
uid <- [Document]
favoriteNames: ["Ana", "Jane", "Dave"] <- [Array]
uid<- [Document]
favoriteNames: ["Ana", "Merry", "John"] <- [Array]
I want to remove "Ana" from all documents. This is what I tried:
usersRef.whereArrayContains("favoriteNames", FieldValue.arrayRemove("Ana").get()
But it doesn't work. How can I remove "Ana" from all arrays?
Upvotes: 2
Views: 1167
Reputation: 317372
It's not possible to do a SQL-like "update where" type query with Firestore. If you have multiple documents to update, you will have to update each one individually. You can use a transaction or batch write to do all the updates atomically, if needed.
Minimally, what you will have to do here is:
Query for all the documents to update. This will involve doing an array-contains query for all "Ana".
usersRef.whereArrayContains("favoriteNames", "Ana")
Iterate the query results.
For each matching DocumentSnapshot, get its DocumentReference and use update()
with FieldValue.arrayRemove("Ana")
snapshot.reference.update("favoriteNames", FieldValue.arrayRemove("Ana"))
Upvotes: 3
Reputation: 20616
If I'm not getting your question wrong you want from one array remove a specific item, in this case "Ana". I've created a sample doing so, let me know if is what you are looking for.
fun main() {
val a = arrayListOf("Joan", "Skizo", "Ana")
val b = a.minus("Ana")
print(b)
}
What is printing is
[Joan, Skizo]
To do so, you can use minus
Returns a list containing all elements of the original collection without the first occurrence of the given element.
Regarding this answer
you'd have to read, write what you want and then remove them from the list and then write it back.
Also this might help you with the update
method I'd say :
https://googleapis.dev/nodejs/firestore/latest/FieldValue.html#arrayRemove-examples
This question might help you also remove array elements in firebase
Upvotes: 1