user3711927
user3711927

Reputation: 35

how to remove parents in firebase by its nested data?

such data comes to the database

{
  "Markers" : {
    "brTRf3EfqzaWuaw0q42Ay8Jnj0F3" : {
      "-M5Tp8BZpUkJSbmV4Qya" : {
        "date" : "22, апр., 2020",
        "latitude" : "53.9150522051367",
        "longitude" : "27.440601512789726",
        "permission" : false,
        "time" : "01:21"
      },
      "-M5XhMon2UZiD6M_Zbp5" : {
        "date" : "22, апр., 2020",
        "latitude" : "53.914562076017575",
        "longitude" : "27.441855780780315",
        "permission" : false,
        "time" : "19:25"
      }
    }
  }
}

Take for example the first entry from the user: brTRf3EfqzaWuaw0q42Ay8Jnj0F3

He put a mark on the map with his parent: "-M5Tp8BZpUkJSbmV4Qya" and it contains a record with time data: "time": "01:21"

Actually the question: how to delete a parent record "-M5Tp8BZpUkJSbmV4Qya" by recording time in it ???

Upvotes: 0

Views: 148

Answers (1)

Peter Haddad
Peter Haddad

Reputation: 80914

To delete the parent according to the query, do the following:

DatabaseReference markerRef = FirebaseDatabase.getInstance().getReference().child("Markers");
markerRef.child("brTRf3EfqzaWuaw0q42Ay8Jnj0F3").orderByChild("time").equalTo("01:21").addListenerForSingleValueEvent(new ValueEventListener() {
         @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
          for(DataSnapshot data: dataSnapshot.getChildren()){
               data.getRef().removeValue();
                  }
            }

        @Override
       public void onCancelled(DatabaseError databaseError) {
                   throw databaseError.toException();
               }
          });

First add a reference to the node brTRf3EfqzaWuaw0q42Ay8Jnj0F3, then using orderByChild("time").equalTo("01:21") you can create a query to retrieve the node that contains the above time. Then iterate inside the snapshots and using getRef() you can obtain a reference to the source location for this snapshot.

Upvotes: 1

Related Questions