For complicated reasons I need to map an array of node IDs to a list of node bundles. That is, for a given list of node IDs, I need to get all the different bundles (node types) of the nodes the IDs belong to. The simple approach would be to load all the nodes, map that to their bundles and using array_unique to get the final list. Unfortunately, this is not a good solution because there may be hundreds of IDs in the array and loading all those nodes will result in a bad performance hit and/or go over the memory limit.

What is the best way to map an array of node IDs to (unique) node bundle types? Is there something built-in or does this require a custom database query? If so, I would be grateful for a dynamic query I could use for this (we're using MySQL). Thanks!

2 Answers 2


Rather than trying to load all nodes, you can query the DB directly for the nid/type (Bundle) pairs you need. Query the node_field_data table and use the IN operator to retrieve all the relevant nids you need.

$nids = [1, 2, 3];
//@TODO: add select query on node_field_data
$query->condition('nid', $nids, 'IN');
//@TODO: execute query and array map results

See the drupal.org docs on using IN operator in dynamic queries.

  • Thanks, I did end up writing a database query for this. I have added the completed query as a separate answer below.
    – MoritzLost
    Commented Aug 4, 2020 at 9:26

For reference, here's the query I used to get this result:

$nodeIds = [1, 2, 3]; // array of node ids
$query = \Drupal::database()->select('node_field_data', 'n');
$query->condition('nid', $nodeIds, 'IN')
    ->fields('n', ['type'])
$nodeTypes = $query->execute()->fetchCol('type');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.