rashidnk
rashidnk

Reputation: 4292

How to query Firebase for value between two keys

How can i search firebase data with a value, i want to get the data if the value comes in between the two keys

Example

If user enter any number between 1 to 5 return the below data,

"start" : "1",
"end" : "5",

"end" key can be empty, the array i have in my firebase database is below

"classdata" : [ null, {
      "-L4VflG9efJfNOk0ETjK" : {
        "start" : "1",
        "end" : "2",
        "classdate" : 1517761011016,
        "commentator" : "",
        "description" : "",
        "id" : 1517745488337,
        "title" : "12"
      },
      "-L4WUbRH46l3pIcwDC2z" : {
        "start" : "3",
        "end" : "",
        "classdate" : 1518961333727,
        "commentator" : "",
        "description" : "",
        "id" : 1517759080685,
        "title" : "5"
      },
      "-L4WbgyUB7MRVUzBNJM3" : {
        "start" : "4",
        "end" : "6",
        "classdate" : 1518975293250,
        "commentator" : "",
        "description" : "",
        "id" : 1517761201012,
        "title" : "2"
      },
      "-L5cxhQzDkEHrFi6J5Mf" : {
        "start" : "7",
        "end" : "",
        "classdate" : 1519010573333,
        "commentator" : "",
        "description" : "",
        "id" : 1518958204014,
        "title" : "1"
      },

Upvotes: 0

Views: 857

Answers (2)

Arnold Gandarillas
Arnold Gandarillas

Reputation: 4322

As @Peter Haddad said "firebase only allows to query on one field" so what you can do to solve your issue is:

firebase.database().ref('classdata')
  .orderByChild('start')
  .startAt(1)
  .once('value', function (snapshot) {
    snapshot.forEach(function(childSnapshot) {
      var childKey = childSnapshot.key;
      var childData = childSnapshot.val();

      // Here you filter by your second field
      if (childData.end === '' || childData.end <= 5) {
        ...
      }
    });
  })

You can find here more documentation about how to filter data in firebase.


Here you can find some really good approaches to resolve your issue.

Upvotes: 0

Peter Haddad
Peter Haddad

Reputation: 80934

You can only query on one child so either start or end child.

What you can do is this:

ref.orderByChild("start").equalTo("4").on(...){...};

The above will give you the values when start=4

ref.orderByChild("start").limitToFirst(5).on(...){..};

this will give you the first 5 of child start

ref.orderByChild("start").startAt("1").endAt("5").on(..){..};

Upvotes: 1

Related Questions