Chirag Mittal
Chirag Mittal

Reputation: 1548

How to get children with a value not equal to 0

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 ?

Upvotes: 2

Views: 1083

Answers (3)

Prashant Saini
Prashant Saini

Reputation: 3539

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);

Upvotes: 0

Ben P.
Ben P.

Reputation: 54194

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);

Upvotes: 3

vikas kumar
vikas kumar

Reputation: 11018

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

Upvotes: 0

Related Questions