GraphQL filtering an array

3.2k Views Asked by At

I am using GatsBy GraphiQL to write a query to return a single element, but the query returns all of the elements. Here is my testing data:

    {
      "data": {
        "mKT": {
          "data": [
            {
              "name": "Apple",
              "description": "apple's desc"
            },
            {
              "name": "Orange",
              "description": "orange's desc"
            },
            {
              "name": "Banana",
              "description": "banana's desc"
            }
          ]
        }
      },
      "extensions": {}
    }

And, here is the GraphQL query:

    query MyQuery {
      mKT(data: {elemMatch: {name: {eq: "Apple"}}}) {
        data {
          name
          description
        }
      }
    }

I expect to get:

    {
     "name": "Apple",
     "description": "apple's desc"
    }

However, running the query returns all of the data. Any idea how to fix this issue?

2

There are 2 best solutions below

2
On

Simply use:

query MyQuery {
  mKT(data: {filter: {name: {eq: "Apple"}}}) {
    data {
      name
      description
    }
  }
}

The filter keyword should do the trick.

Check the GraphQL Reference (in Gatsby docs) for further details.

0
On

I believe this is the same case as:

GraphQL query to access first item in an array?

You cannot use filters, limits, etc to an structure if it have not been defined on the source.

If you have access to the source, add something like limit to the field data.

If not, you will get the full array, and you have to process it on your side.