Minecraft – How to execute command for villagers with certain NBT tags

minecraft-commandsminecraft-java-edition

In Java Minecraft 1.14, I tried to use the execute command as basics. And on some NBT Tags, it works (e.g. XP: /execute as @e[type=minecraft:villager] if entity @s[nbt={Xp:0}] run tp @p), but for most, it does not.

I especially tried to run commands for villagers of certain professions, and my best attempt was /execute as @e[type=minecraft:villager] if entity @s[nbt={VillagerData:{Profession:farmer}}] run tp @p, but – as far as I understand – it detects no entities at all, no matter what entities exist (because without the run part of both commands the first one tests for all villagers that meet the conditions successfully with – logically – one detected, but the second has just no output whatsoever).

Best Answer

In short, you need to put profession:"minecraft:farmer". An explanation of how I found that out:

The Chunk Format wiki page is very helpful for this kind of thing. If you scroll down to the list of entities and expand the Villager entry, and then the villager profession portion (which is nested within the villager entry) you can see the data tree for the villager. You can see that VillagerData is a compound tag, and one of the possible nested tags is profession (note the lowercase p) which needs a String data type (see this), so the value needs to be enclosed in quotation marks. One of the possible values is minecraft:farmer, so therefore you would want to use

/execute as @e[type=villager,nbt={VillagerData:{profession:"minecraft:farmer"}}] run tp @s @p

I took the liberty of combining your as @e and if entity statements, because it is more concise and readable, and clarifying that @s (the villager) is being teleported to @p (the nearest player to the executing location). You could even get really crazy and shorten it even more to be /tp @e[type=villager,nbt={VillagerData:{profession:"minecraft:farmer"}}] @p.