如official documentation:
虽然 Cloud Firestore 可以存储数组,it does not support 查询数组成员或更新单个数组元素。
所以没有办法可以使用以下查询:
collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")
如果您只想获取整个 userId 数组,则需要像这样遍历 Map:
collection("mychannel").document("1fReXb8pgQvJzFdzpkSy").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("userId")) {
Log.d("TAG", entry.getValue().toString());
}
}
}
}
}
});
但请注意,即使 userId 对象作为数组存储在数据库中,entry.getValue() 也会返回 ArrayList,而不是 array。
所以输出将是:
[74wRU4xHrcV9oWAXEkKeRNp41c53]
如果您考虑这种替代数据库结构,更好的方法将是,其中每个用户 ID 都是地图中的键,所有值都是 true:
userId: {
"74wRU4xHrcV9oWAXEkKeRNp41c53": true,
"AdwF...": true,
"YsHs...": true
}