Conditionally unpublish a nodes more than latest 20
You need an entity query to get the nodes filtered by the content type, sorted by the changed or created date and starting with the 21th node:

  $query = \Drupal::entityQuery('node');
  $nids = $query
    -&gt;condition('type', $type)
    -&gt;sort('changed', 'DESC')
    -&gt;range(20, PHP_INT_MAX)
    -&gt;execute();
  $nodes = Node::loadMultiple($nids);


You could also add a condition for published nodes, so that you don't load nodes that don't need to be unpublished:

    -&gt;condition('status', NodeInterface::PUBLISHED)