chackerian
chackerian

Reputation: 1401

Check for identical value in firebase collection

How would you implement a matching system to check when two values are the same in one collection from different documents? This code has to call a function to run every-time it detects that the two values are matching.

Upvotes: 1

Views: 456

Answers (1)

Divyani Yadav
Divyani Yadav

Reputation: 1142

As mentioned in the documentation :

Cloud Firestore provides powerful query functionality for specifying which documents you want to retrieve from a collection or collection group. These queries > can also be used with either get() or addSnapshotListener(), as described in Get Data and Get Realtime Updates.

I will recommend you to use a unique identifier for each entry and then you can add a listener that will match each data from the collections. Syntax :

 query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override public void onDataChange(DataSnapshot dataSnapshot) { 
    if (dataSnapshot.exists()) { 
    // dataSnapshot is the "issue" node with all children with id 0
     for (DataSnapshot issue : dataSnapshot.getChildren()) {
     // do something with the individual "issues"
} } }

You can refer to the Stackoverflow answer where Frank has explained it briefly with the following function code.

public interface AlreadyBookedCallback {
  void onCallback(boolean isAlreadyBooked);
}

private void alreadyBooked(final String boname, final String bodept, final String botime, AlreadyBookedCallback callback) {
    CollectionReference cref=db.collection("bookingdetails");
    Query q1=cref.whereEqualTo("time",botime).whereEqualTo("dept",bodept);
    q1.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
        @Override
        public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
            for (DocumentSnapshot ds : queryDocumentSnapshots) {
                String rname, rdept, rtime;
                rname = ds.getString("name");
                rdept = ds.getString("dept");
                rtime = ds.getString("time");
                if (rdept.equals(botime)) {
                    if (rtime.equals(botime)) {
                        isExisting = true;
                    }
                }
            }
            callback.onCallback(isExisting)
        }
    });
}

For more information you can also refer to this thread on how to check duplicate values in documents.

Upvotes: 1

Related Questions