Home > Net >  Firestore database java add where condition before get collection
Firestore database java add where condition before get collection

Time:06-15

I am using the Firestore database for my web application. When I query documents from a collection I need to append a where condition. Is there any method available to append specific conditions before fetch CollectionReference?

CollectionReference collectionReference = dbFirestore.collection("collectionName").someMethod("Where conditions to fetch specific documents")

Or any other options to send a full query with conditions from Java or Spring to Firestore and get results? I don't want to have database codes in my front-end designs. If no other option, I would end up using javascript to do so. But it would be not a proper design.

Query query = dbFirestore.collection("collectionName").whereEqualTo("colmn1", "value").whereEqualTo("column2", "value");

How to iterate values from query (com.google.cloud.firestore.Query) object?

CodePudding user response:

If you need to get the result of the following query:

Query query = dbFirestore.collection("collectionName").whereEqualTo("colmn1", "value").whereEqualTo("column2", "value");

You have to call get(), and then attach a listener, as you can see in the following lines of code:

query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                if (document != null) {
                    //Get the data out from the document.
                }
            }
        } else {
            Log.d(TAG, task.getException().getMessage()); //Never ignore potential errors!
        }
    }
});

If you're using Java for a Non-Android project, then you should consider using the following lines of code:

ApiFuture<QuerySnapshot> future = dbFirestore.collection("collectionName").get();
QuerySnapshot querySnapshot = future.get();
List<QueryDocumentSnapshot> documents = querySnapshot.getDocuments();
ArrayList<String> ids = new ArrayList<>();
ArrayList<String> names = new ArrayList<>();
for (QueryDocumentSnapshot document : documents) {
    String docId = document.getId();
    ids.add(docId);
    System.out.println(docId);
    String name = document.getString("name");
    names.add(name);
    System.out.println(name);
}
  • Related