[英]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.