Bruxism. Teeth grinding, especially during sleep is not uncommon. It can be a big problem, as grinding one's teeth can wear off the enamel. The enamel does not grow back and one can then have further dental problems down the road. Most pharmacies have bite blocks to be used to prevent this. You might go to the dentist and have your teeth checked out. I try low dose nortriptyline for my bruxism patients.
Stress response. Bruxism is often related to stress, so a nightmare can certainly induce the response. How do you know you only grind your teeth during this time since you are asleep? Has someone observed this? I would suspect you are doing at other times during sleep as well. Speak to your dentist to discuss methods of protection as well as other potential causes.