MikeL
MikeL

Reputation: 173

Checking if database value is greater than local value in Firebase

I think this is simple but can't seem to create the correct query. I'm using Swift with Firebase Realtime Database on iOS.

Consider the following Firebase structure:

-DATA
--UID
---LEVEL1
----HIGHSCORE

I am trying to create a query to find out whether the specific HIGHSCORE number for a level is greater than a local variable. If it is, I want the return to be the higher value from Firebase. If it is the same or lower, I want the return to be null.

I have tried many different queries, here is an example:

ref.child("DATA/UID/LEVEL1/HIGHSCORE").queryStarting(atValue: 5000).observeSingleEvent(of: .value, with:

I know this is fundamentally incorrect, but I think it shows what I am trying to do.

Thanks in advance for any help.

Mike

EDIT: Here is the actual JSON example:

{
 "DATA" : {
    "USERID" : {
      "LEVEL1" : {
        "HIGHSCORE" : 5000,
      }
    }
  }
}

Upvotes: 1

Views: 765

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599581

The only way I can think of is with an orderByValue:

ref.child("DATA/UID/LEVEL1").orderByValue().queryStarting(atValue: 5000).observeSingleEvent(of: .value, with:

But this only works well if HIGHSCORE is the only child node under LEVEL1. Even then: it doesn't have any bandwidth or performance over the more idiomatic approach:

ref.child("DATA/UID/LEVEL1/HIGHSCORE").observeSingleEvent(of: .value, with: { (snapshot) in 
  if snapshot.exists() {
    val score = snapshot.value as! Int
    if score > 5000 {
      ...
    }
  }
})

Upvotes: 1

Related Questions