Let’s say we have a database with sub-items turned on like so:

Untitled

How would we, for each of our pages, count how many sub-items are nested under each page recursively?

So for Example 1 above, we’d like to see a total of 5 pages because the following pages are nested underneath (Below we can see 5 pages highlighted by using a filter that matches pages starting with “Example 1-”):

Untitled

We can use recursion up to 15 levels deep with Formulas and Rollups. Past that, your formula will stop working.

To total up the number of sub-items at any depth (up to 15, of course), we can first build a list of sub-items as Children. This assumes you have enabled sub-items and the name of the property is Sub-item

Children

if(
  /* No sub-items, return an empty list */
	prop("Sub-item").empty(),
	[],
	
	/**
	 * Get children of sub-items as "ancestors". Note here that we are referring
	 * to "Children" from the Children formula. This is where the recursion happens.
	 */
	let(
		ancestors,
		prop("Sub-item").map(current.prop("Children")),
		
		/* Do the children have any children themselves? */
		if(
			ancestors.empty(),
			
			/* Just return the sub-items */
			prop("Sub-item"),
			
			/** 
			 * Because sub-items are a list, we have to add them to the ancestors
			 * list and flatten this list to make it a single dimension.
			 */
			prop("Sub-item").concat(ancestors).flat()
		)
	)
)

We can then total up the sub-items nested down to 7 levels deep with:

Total Sub-items

prop("Children").length()

Here’s the result. Feel free to expand the toggles to see the counts at different depths.