Join us live Sept. 27 – How Sanity and Vercel powered Morning Brew's transformation –>

GROQ Query for new and unpublished Documents

By Simeon Griggs & Peter

Not all Unpublished Documents are created equal

Querying for Draft Documents

{
  "unpublishedAll": *[_id in path("drafts.**")],
  "unpublishedNew": *[_id in path("drafts.**") && count(*[^._id == "drafts." + _id]) == 0],
  "unpublishedModified": *[count(*[_id in [^._id, "drafts." + ^._id]]) > 1]
}

Draft / Unpublished Documents can be queried by looking for any Document which has an _id that begins with drafts. but determining if the Document has ever been Published before requires more work.

An existing, previously published Document with unpublished changes will exist as two Documents that can be returned by an authenticated query, their _id's look something like:

  • asdf-1234
  • drafts.asdf-1234

However, a new Document that has never been published will only exist with an _id that begins with drafts.

When this snippet is run, the number of results in unpublishedAll should equal the sum of the results in unpublishedNew and unpublishedModified.

Note: These example queries are not optimised and are intended for use cases like document lists for your Dashboard.

The three query keys explained:

  1. unpublishedAll will return all Documents with an _id beginning with drafts.
  2. unpublishedNew does the same search but only returns Documents for which it can also find Published _id's.
  3. unpublishedModified finds as many Documents where both a published and draft _id for the same document exist.

Contributors

Simeon Griggs

πŸ‡¦πŸ‡Ί in πŸ‡¬πŸ‡§ Solution Engineer @ Sanity

Simeon is located at Newcastle upon Tyne, UK
Visit Simeon Griggs's profile

Other schemas by authors