如何从Firestore获取对象数组 [英] How to get an Array of Objects from Firestore

查看:269
本文介绍了如何从Firestore获取对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查询作为地图数组的字段的正确方法是什么。

What would be the right way to query a field that is an array of maps.

目前结构是

Collection1
     Document1
         -papers:                <---- This is an array  
              (0): 
                 -Name:abc
                 -Id:123 
              (1): 
                 -Name:xyz
                 -Id:456

这是我的代码

DocumentReference docRef = db.collection("Collection1").document("Document1");
        docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if (task.isSuccessful()) {
                    DocumentSnapshot document = task.getResult();
                    if (document != null && document.exists()) {
                       //?? how can I retrieve papers
                }
            }
        });

我基本上检索它并将其转换为ArrayList>然后循环遍历它以创建我的最终版本ArrayList?

Basically do I retrieve it and cast it as an ArrayList> and then loop through it to create my final ArrayList ?

或者它是如何工作的?

推荐答案

按照有关阵列的官方文档


虽然Cloud Firestore可以存储数组, 但它不支持 查询数组成员或更新单个数组元素。

Although Cloud Firestore can store arrays, it does not support querying array members or updating single array elements.

如果您只想获得整个论文数组,则需要迭代 Map ,如下所示:

If you only want to get the entire papers array you need to iterate over a Map like this:

Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (entry.getKey().equals("papers")) {
        Log.d("TAG", entry.getValue().toString());
    }
}

但请注意,即使论文对象作为数组存储在数据库中, entry.getValue()返回 ArrayList ,而不是数组

But note, even if papers object is stored in the database as an array, entry.getValue() returns an ArrayList, not an array.

编辑2018年8月13日:

根据有关数组成员资格,现在可以使用 whereArrayContains()方法根据数组值过滤数据。一个简单的例子是:

According to the updated documentation regarding array membership, now it is possible to filter data based on array values using whereArrayContains() method. A simple example would be:

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




此查询返回每个城市文档,其中regions字段是一个数组包含west_coast。如果数组具有您查询的值的多个实例,则文档仅包含在结果中一次。

This query returns every city document where the regions field is an array that contains west_coast. If the array has multiple instances of the value you query on, the document is included in the results only once.

这篇关于如何从Firestore获取对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆