如何获取DocumentSnapshot id作为字符串?

时间:2019-02-27 21:35:56

标签: java android google-cloud-firestore

如何在Firestore中获取文档的ID?

final String PostKey = db.collection("Anuncio").document().getId();

我正在尝试这种方式,但是它返回一个新的ID。如何获得已经存在的文档的ID?

1 个答案:

答案 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());
                }
            }
        });