GROQ Queries

Some different ways to use functions in sanity.io's GROQ to create some counts in your queries.

counting posts by a given type

count(*[_type == "post"]) // counting number of entries of type "post"

// in a query with other things
{
 ...,
 "postCount": count(*[_type == "post"]),
 ...
}

counting items that reference a given document

// count items that reference each category
*[_type == "category"]{ 
   _id, 
   title, 
   "numPosts": count(*[references(^._id)]) // number of posts that reference this category's _id, if that's how you reference them
}

gettiing all documents of a type, and manipulating the amount of results

// get all documents of type "post"
*[_type == "post"]{_id, title} //list of fields 

// get 10 most recent documents of type "post"
*[_type == "post"] | order(publishedAt desc) {_id, title}[0...10]

// get 10 most recent documents of type "post" by date
*[_type == "post"] | order(publishedAt desc) {_id, title}[0...10]

// get list of documents that reference each one in a general query 
// e.g. get all posts, get the comments of the post, and then get replies to each comment)
*[type == "post"] | order(publishedAt desc) {
   _id, 
   title,
   "comments": *[_type == "comment" && references(^._id)] {
      _id, 
      body, 
      name, 
      "replies": *[_type == "comment" && references(^._id)] | order(publishedAt desc) {
         _id, 
         body,
         name
      }
    }
  }