簡體   English   中英

Android Firestore查詢獲取包含搜索中的值的文檔的ID

[英]Android Firestore query get the id of the document that contains the value in the search

Firestore數據庫映像

您好,我只是嘗試使用Firestore。 獲取文檔ID時出現問題。

問題是,我想獲取其中包含值(藍色框)的文檔ID(紅色框)。

我使用以下查詢:

collection("mychannel").whereEqualTo("74wRU4xHrcV9oWAXEkKeRNp41c53")

但是沒有給出結果。

謝謝!

官方文檔中所示

盡管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]

如果考慮這種替代數據庫結構,則更好的方法是,其中每個用戶標識是映射中的鍵,並且所有值都為true:

userId: {
    "74wRU4xHrcV9oWAXEkKeRNp41c53": true,
    "AdwF...": true,
    "YsHs...": true
}

在這里回答此問題: Firestore:按文檔數組中的項目進行查詢

總而言之,請勿使用數組將數據存儲在Firestore中,因為您要執行的查詢尚不可用(請記住它仍處於beta中)。 您應該改為使用地圖。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM