问题描述
我有一组用户.每个用户都有一个名为 favoriteNames
的数组.
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]
我要删除"Ana"从所有文件.这是我尝试过的:
I want to remove "Ana" from all documents. This is what I tried:
usersRef.whereArrayContains("favoriteNames", FieldValue.arrayRemove("Ana").get()
但是它不起作用.如何删除"Ana"来自所有阵列?
But it doesn't work. How can I remove "Ana" from all arrays?
推荐答案
无法执行类似SQL的"update where"使用Firestore输入查询.如果要更新多个文档,则必须分别更新每个文档.如果需要,您可以使用事务或批处理写入来自动进行所有更新.
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.
至少,您要做的是:
-
查询所有要更新的文档.这将涉及对所有"数组包含查询进行; Ana".
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.
对于每个匹配的 DocumentSnapshot ,获取其DocumentReference并将 update()
与 FieldValue.arrayRemove("Ana")
For each matching DocumentSnapshot, get its DocumentReference and use update()
with FieldValue.arrayRemove("Ana")
snapshot.reference.update("favoriteNames", FieldValue.arrayRemove("Ana"))
这篇关于如何从Firestore中的多个文档中的数组中删除元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!