NullHypothesis
NullHypothesis

Reputation: 4506

Get documents in Firebase where field is X in Swift 4

I am looking to retrieve all documents from my collection in Swift where the field "groupId" == "31bc2501-7164-4f22-7b28-9f9005acbcf6" (a guid)

If I use the firebase document id, then that works:

i.e.

CollectionReference reference = db.collection("chats/XIiOrtRiYmLtzz1tzG2u")

but I want to query it by a field instead.

I see in Swift there is stuff like this:

var query = db.collection("chats").whereField("groupId", isEqualTo: "31bc2501-7164-4f22-7b28-9f9005acbcf6")

but it returns a query object, and I can't figure out how to "pop" it to execute the query and return to me a collection (most of the examples online seem to use different and outdated syntaxes to do this, and don't use whereField)

is there a way to query a collection inline like I did in the first example but using other fields than the primary key? Perhaps I'm querying the collection incorrectly?

Thanks, appreciate your time!

Upvotes: 0

Views: 5043

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598857

From the Firebase documentation on getting multiple documents through a query:

db.collection("chats").whereField("groupId", isEqualTo: "31bc2501-7164-4f22-7b28-9f9005acbcf6")
  .getDocuments() { (querySnapshot, err) in
    if let err = err {
        print("Error getting documents: \(err)")
    } else {
        for document in querySnapshot!.documents {
            print("\(document.documentID) => \(document.data())")
        }
    }
}

Upvotes: 4

Related Questions