- Published on
Gatsbyjs GraphQL Filtering on Multiple Fields
- Authors
- Name
- Yair Mark
- @yairmark
I use GatsbyJS to create my blog. One of the things that bugged me which I could not find a definite answer for online was how do you filter by more than one field in your GraphQL queries?
For example I have:
{
allMarkdownRemark(
filter: { id: { regex: "//posts|pages//" } }
sort: { fields: [frontmatter___date], order: DESC }
) {
edges {
node {
objectID: id
fields {
slug
}
internal {
content
}
frontmatter {
title
subTitle
}
}
}
}
}
In the above I am filtering out anything that is a post or page but I also want to only return posts/pages that have been published. In my case I control this using the frontmatter publish
field which is true or false. After a bit of Googling I tried to simply add a comma after the first filter's }
and it worked!
{
allMarkdownRemark(
filter: { id: { regex: "//posts|pages//" }, frontmatter: { publish: { eq: true } } }
sort: { fields: [frontmatter___date], order: DESC }
) {
edges {
node {
objectID: id
fields {
slug
}
internal {
content
}
frontmatter {
title
subTitle
}
}
}
}
}
While GraphQL is JSON like it is not JSON, but it has similar syntax in some cases it seems like listing multiple properties in a JSON object for example.
I have not worked with GraphQL outside of GatsbyJS but I do not think this will work on vanilla GraphQL as GatsbyJS uses Sift to give GraphQL more MongoDB query capabilities including filtering as described here:
Gatsby relies on Sift to enable MongoDB-like query syntax for object filtering.