在Android Studio中用Where子句获取Firebase Firestore文档ID
获取Firestore中指定条件的文档ID
当你通过where子句查询到匹配的文档后,每个文档快照对象都直接包含文档ID,你只需要访问对应属性即可,以下是各平台的实现示例:
Web(JavaScript)
import { collection, query, where, getDocs } from "firebase/firestore"; // 替换成你的集合名称 const q = query(collection(db, "你的集合名"), where("Name", "==", "Karan Bapat")); const querySnapshot = await getDocs(q); querySnapshot.forEach((doc) => { console.log("匹配的文档ID:", doc.id); // 如需获取文档数据,可使用 doc.data() });
Android(Kotlin)
val db = FirebaseFirestore.getInstance() val collectionRef = db.collection("你的集合名") val query = collectionRef.whereEqualTo("Name", "Karan Bapat") query.get().addOnSuccessListener { querySnapshot -> for (document in querySnapshot) { println("匹配的文档ID:${document.id}") // 如需获取文档数据,可使用 document.data } }
iOS(Swift)
let db = Firestore.firestore() let collectionRef = db.collection("你的集合名") let query = collectionRef.whereField("Name", isEqualTo: "Karan Bapat") query.getDocuments { (querySnapshot, error) in if let error = error { print("查询失败:\(error)") return } guard let documents = querySnapshot?.documents else { print("未找到匹配的文档") return } for document in documents { print("匹配的文档ID:\(document.documentID)") // 如需获取文档数据,可使用 document.data() } }
核心说明:所有Firestore SDK返回的文档对象都自带文档ID属性,只需在遍历查询结果时读取该属性即可,无需额外的查询操作。
内容的提问来源于stack exchange,提问作者Viraj Yekhe
相关产品推荐
相关产品推荐

