![](/img/trans.png)
[英]Can I query and retrieve Documents' field values in Subcollection in Cloud Firestore?
[英]How can I retrieve a specific field from a map in Cloud Firestore using Android?
这是 Firebase Firestore 中保存的数据的一部分:
如何从 Java 中的 ( newFriend0
) 获取 ( fName
)?
这是代码的一部分。 它给出了整个地图。 我只想要一个特定的字段,例如 ("jem" for (fName))
Map<String, Object> map = document.getData();
for (Map.Entry<String, Object> entry : map.entrySet()){
if (entry.getKey().equals("Friends")){
f=document.getString("FName");////not worked
Log.d("TAG", entry.getValue().toString());
}
}
编辑: 2201 年 7 月 16 日
事实上,有一种更简单的方法来获取这些数据:
看到你的代码是Java,请看下面的解决方法:
FirebaseFirestore.getInstance().collection("coll").document("9999").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> friendsMap = document.getData();
for (Map.Entry<String, Object> entry : friendsMap.entrySet()) {
if (entry.getKey().equals("Friends")) {
Map<String, Object> newFriend0Map = (Map<String, Object>) entry.getValue();
for (Map.Entry<String, Object> e : newFriend0Map.entrySet()) {
if (e.getKey().equals("newFriend0")) {
Map<String, Object> fNameMap = (Map<String, Object>) e.getValue();
for (Map.Entry<String, Object> dataEntry : fNameMap.entrySet()) {
if (dataEntry.getKey().equals("fName")) {
Log.d("TAG", dataEntry.getValue().toString());
}
}
}
}
}
}
} else {
Log.d("TAG", "No such document");
}
} else {
Log.d("TAG", "get failed with ", task.getException());
}
}
});
您的 logcat 中的结果将是:
jem
在屏幕截图中没有看到您收藏的名称,因此我将其简单地命名为coll
但您绝对应该将其更改为正确的名称。
基本上,您需要执行 2 个步骤,使用提供的库之一检索文档数据,然后使用您的编程语言操作生成的地图对象。
这是一个获取“fName”的简单 Nodejs 示例:
let docRef = db.collection('<collection_name>').doc('9999');
docRef.get()
.then(doc => {
if (!doc.exists) {
console.log('No such document!');
} else {
console.log('Document data:', doc.data().Friends.newFriend0.fName);
}
})
.catch(err => {
console.log('Error getting document', err);
});
Firestore 文档是 JSON 格式,因此我们可以先将documentSnapshot.getData()
转换为 String 然后再转换为 JSON,这样访问 Map 对象数据会更容易,而无需太多循环/迭代。 另一种方法是像这样documentSnapshot.getData().get("get_only_map_key_to_be_converted_as_JSON")
将其转换为字符串,然后也转换为 JSON。 可能剩下的问题是,如果您将 url 存储在文档的地图对象中,这将出现问题,因为这些链接需要取消转义才能成为有效的 JSON,尽管我还没有在 Android Java 中尝试过这种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.