2

Consider the following JSON format in Firebase database -

"root":
{
    "question":
    {
        "1":
        {
            "category":"A",
            "replies":0
        },
        "2":
        {
            "category":"B",
            "replies":1
        },
        "3":
        {
            "category":"B",
            "replies":0
        },
        "4":
        {
            "category":"C",
            "replies":2
        }
    }
}

For getting all questions with replies = 0, I do,

Query query = rootReference.child("question").orderByChild("replies").equalTo(0);

which works perfectly.

But what should I do if I want those questions with replies not equal to 0 ?

Chirag Mittal
  • 1,508
  • 1
  • 12
  • 17

3 Answers3

3

Reading the documentation, I see no notEqualTo() method or any other way to "negate" a query. However, since you're already calling .orderByChild("replies"), you could perhaps use this:

Query query = rootReference.child("question").orderByChild("replies").startAt(1);
Ben P.
  • 52,661
  • 6
  • 95
  • 123
0

Firebase currently supports only positive operations, not the negation. so you may want to retrieve all the data and then filter it locally.

Here is full answer

vikas kumar
  • 10,447
  • 2
  • 46
  • 52
0

Actually Firebase doesn't provide any method to exclude some results like you are seeking here.

However, you can modify your JSON like this & then use following query:

// add a different key for all replies = 0, & another different key for non-zero replies
"root":
{
    "question":
    {
        "1":
        {
            "category":"A",
            "replies":0,
            "key2":"someOtherKey"
        },
        "2":
        {
            "category":"B",
            "replies":1,
            "key1":true
        },
        "3":
        {
            "category":"B",
            "replies":0,
            "key2":"someOtherKey"
        },
        "4":
        {
            "category":"C",
            "replies":2,
            "key1":true
        }
    }
}

// now you can use this query to get all non-zero-replies results
// it will give you child 2, 4
Query query = rootReference.child("question").orderByChild("key1").equalTo(true);

// to get all zero-replies childs, use this
Query query = rootReference.child("question").orderByChild("key1").equalTo(null);
Prashant Saini
  • 3,539
  • 1
  • 10
  • 24