簡體   English   中英

如何在 Android 上使用 whereArrayContains() 過濾器查詢包含 Firestore 集合中對象數組的文檔?

[英]How to query documents containing array of objects in Firestore collection using whereArrayContains() filter on Android?

我在 firestore 中有一個集合,其中每個文檔都包含一個聯系人數組,我想查詢那些任何聯系人的 email id 都是特定值的文檔。

我在https://firebase.google.com/docs/reference/android/com/google/firebase/firestore/Query#whereArrayContains(java.lang.String,%20java.lang.Object)遇到了 whereArrayContains() 過濾器,具有以下描述:-

public Query whereArrayContains(字符串字段,Object值)
創建並返回一個帶有附加過濾器的新查詢,文檔必須包含指定的字段,該值必須是一個數組,並且該數組必須包含提供的值。

一個查詢只能有一個 whereArrayContains() 過濾器。

上述方法中的value是否可以指向對象數組的 object 中的字段?

此外,鑒於方法參數也稱為value ,短語the value must be an array有點令人困惑。 我確信文檔意味着該field應該出現在文檔中並且它的值應該是一個數組並且該數組應該包含value參數。

您無法在 Firestore 查詢中查詢數組中的對象字段。 array-contains 查詢將與數組中的對象進行比較。

該值必須是一個數組

這是指您嘗試查詢的字段的值。 更好的措辭是

創建並返回一個新的查詢與所述額外的過濾器的文檔必須包含指定字段中,指定字段的值必須是一個陣列,並且該陣列必須包含所提供的值。

如果您嘗試過濾用戶 ID 或類似內容,請考慮向您查詢的對象添加第二個數組,然后將 ID 作為字符串添加到該數組中:

{
    "name": "test",
    "users": [someUserObject, someOtherUserObject],
    "userIds": ["someId", "someOtherId"]
}

然后查詢該數組:

someRef.whereArrayContains("userIds", someId);

根據文檔,該字段指向數組,值表示您要檢查的字符串是否存在於數組中。

您可以使用 array_contains 運算符根據數組值進行過濾。 例如:

CollectionReference citiesRef = db.collection("cities");
citiesRef.whereArrayContains("regions", "west_coast");

此查詢返回每個城市文檔,其中區域字段是包含 west_coast 的數組。 如果數組具有您查詢的值的多個實例,則該文檔僅包含在結果中一次。

數據添加為:-

CollectionReference cities = db.collection("cities");

Map<String, Object> data1 = new HashMap<>();
data1.put("name", "San Francisco");
data1.put("state", "CA");
data1.put("country", "USA");
data1.put("capital", false);
data1.put("population", 860000);
data1.put("regions", Arrays.asList("west_coast", "norcal"));
cities.document("SF").set(data1);

正如其他人所說,不可能按照你的要求去做。

“Firebase-y”方式做你想做的,是創建一個子集合而不是一個數組,然后數組中的每個對象都是子集合中的一個文檔。

然后,您可以使用集合組查詢來查詢子集合中的各個字段。

如果您需要訪問父文檔,您可以通過調用訪問它

snapshot.document.parent.parent

它返回一個 DocumentReference。 (文檔的父級是一個集合,所以它的 .parent.parent 來獲取父級文檔)。 然后,您必須重新查詢該參考。

您可以使用 map 而不是像接受的答案那樣使用兩個 arrays,而是像這樣構造您的數據:

{
    users: {
        userId1: {
            name: "...",
            //rest of the fields
        },
        userId2: {
            name: "...",
            //rest of the fields
        }
    }
    //rest of the fields
}

然后使用此查詢按 id 進行過濾

collectionRef.orderBy("users.userId1")

暫無
暫無

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

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