Search code examples
firebasegoogle-cloud-platformgoogle-cloud-firestorerequestpostman

Firebase Firestore REST Request - Query and Filter


I have a firestore database on a firebase project. I want to make rest request for filtering or querying data with postman. I'm using https://firestore.googleapis.com/v1/projects/<myprojectid>/databases/(default)/documents/<path> to get the data in a known path in my database. Here is a sample of my database structure:

users > xxxxx > messages > yyyyy> "sent":"true"

where "users" and "messages" are collections, "xxxxx" and "yyyyy"are autogenerated document ids (xxxxx is autogenerated user id)

What I want to do is to find the "xxxxx"s (users) which have >"sent":"true"< data.

I get success if I know the "xxxxx" and "yyyyy" but I don't know them because they are autogenerated and different from each other in my database and don't know how to do it.


Solution

  • You need to run a Query, as explained here in the documentation of the REST API.

    Since you want to query all the messages sub-collections of different user documents, you need to "simulate" a Collection Group Query in your StructuredQuery. The way to do that is to set the allDescendants element to true in the CollectionSelector.

    So, issuing a POST HTTP Request on the following URL will do the trick:

      var URL = "https://firestore.googleapis.com/v1/projects/<your-project-id>/databases/(default)/documents:runQuery";
    

    The body of the POST Request shall contain:

        "structuredQuery": {
            "from": [{
                "collectionId": "messages",
                "allDescendants": true
            }],
    
            "where": {
                "fieldFilter": {
                    "field": {
                        "fieldPath": "sent"
                    },
                    "op": "EQUAL",
                    "value": {
                        "stringValue": "true",
                    }
                }
            }
        }
    

    Note that you need to add a single field index to your Firestore DB, as follows:

    enter image description here


    Note also that, if your field sent is of type Boolean (and not String as shown in your question), you need to use a booleanValue element in your Value JSON element.