Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

Nested Key Query in Firebase?

Firebase Data Structure

{
  "books": {
    "-KaKjMMw-WQltqxrGEmj": {
      "categories": {
        "cat1": true,
        "cat2": true
      },
      "author": "user1",
      "title": "event1"
    },
    "-KaKjMMw-WQltqxrGEmk": {
      "categories": {
        "cat1": true,
        "cat2": false
      },
      "author": "user1",
      "title": "event2"
    }
  }
}

Query To find all books of a particular author

FNode.testNode.child("books")
    .queryOrderedByChild("author")
    .queryEqualToValue("user1")
    .observeEventType(.Value) { (snapshot) in
    print(snapshot)
}

Question:

I want to find all the books belonging to cat1. Couldn't figure out the query to do that.

Upvotes: 1

Views: 552

Answers (1)

Prajeet Shrestha
Prajeet Shrestha

Reputation: 8108

After a lot of hit and trial, finally got my answer.

For the above structure. If you want to find all the books belonging to cat1 Here is the query for that:

FNode.testNode.child("books")
    .queryOrderedByChild("categories/cat1").queryEqualToValue(true)
    .observeEventType(.Value) { (snapshot) in
    print(snapshot)
}

Note: FNode.testNode could be any node of type FIRDatabaseReference

To Firebase Team: Can you please include a sample of all possible firebase queries in data structures and put it alongside firebase docs. It's kind of hit-and-trial for us now.

Upvotes: 2

Related Questions