Use a carpet cleaner with some vinegar and water and run the carpet cleaner over the carpet.
Vinegar is a natural cleaning solution for carpets and upholstery.
After using the vinegar and water in the carpet cleaner then sprinkle baking soda where the moldy smell is on the carpet and let it sit for 30 minutes to an hour.
Then use the carpet cleaner again with vinegar and water to clean the baking soda out of the carpet.
Make sure to dry the carpet out really good after using the carpet cleaner on the carpet.
You can also use carpet cleaning shampoo or resolve carpet cleaner to remove moldy smells from carpets.