如何在Firestore中获取文档的ID?
final String PostKey = db.collection("Anuncio").document().getId();
我正在尝试这种方式,但是它返回一个新的ID。如何获得已经存在的文档的ID?
答案 0 :(得分:1)
如果您事先不知道文档ID,可以retrieve all the documents in a collection并打印出ID:
db.collection("Anuncio")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});
如果您对文档的子集感兴趣,可以add a query clause来过滤文档:
db.collection("Anuncio")
.whereEqualTo("some-field", "some-value")
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
}
}
});