Home > database >  Is there any way to fetch all of the documents with a specific term inside of Firestore?
Is there any way to fetch all of the documents with a specific term inside of Firestore?

Time:11-05

I have a firebase database that holds some information, and I was hoping to specifically get all of the documents, but with a specific key word. Looking at Image1 below, I was hoping that I could locate in on the Sports Field.

My code for the firebase service:

struct CustomFirestoreService {
    let store: Firestore = .firestore()
    init(){}
    func getAnnotations() async throws -> [Annotation]{
        let ANNOTATIONS_PATH = "annotations"
        return try await retrieve(path: ANNOTATIONS_PATH)
    }
    ///retrieves all the documents in the collection at the path
    private func retrieve<FC : Codable>(path: String) async throws -> [FC]{
        //Firebase provided async await.
        let querySnapshot = try await store.collection(path).getDocuments()
        return querySnapshot.documents.compactMap { document in
            do{
                return try document.data(as: FC.self)
            }catch{
                print(error)
                return nil
            }
        }
    }
}

Annotaion:

struct Annotation: Codable, Identifiable, Hashable {
    @DocumentID var id: String?
    let lat: String?
    let lng: String?
    var name: String
    var sport: String
    var headCoach: String
}

Firebase Data

I've looked around and tried modifying the path to be like: annotations.sport but still no luck.

CodePudding user response:

Given your screenshot, that'd be easy to do with a query:

store.collection(path).whereField("sport", isEqualTo: "Baseball").getDocuments()

I recommend spending some time studying that page start-to-finish, as there are quite a few query operations, and it's good to know of them early on. If you're new to Firestore and NoSQL in general, I also recommend watching Get to know Cloud Firestore.

  • Related