It was about the Soviet Union. The British convinced the US that Mosaddegh was going to align himself with the Soviet-proxy communist party (Tudeh) to stay in power. The British, on the other hand, did it because Iran had nationalized British oil fields. The US' oil interests were in Saudi Arabia.
Also the way people describe this is rather twisted. The Shah was not installed by the US. The Shah had been in power since 1941. He was installed by the British, same as his father. The coup replaced Mosaddegh with Fazlollah Zahedi, not the Shah.
Moreover, Mosaddegh's government was not remotely democratically elected. There's a rather in-depth State department memo from the era that describes how those "elections" worked in Iran which made clear that the people voting had little to do with who won. Elections were full of ballot stuffing, bribery and just outright manipulation by pretty much everyone - the Shah, Mosaddegh, Tudeh, foreign governments, etc. [1]
Plus, Mosaddegh had halted Parliamentary election counting early to prevent more opposition from getting elected risking his majority (his party controlled the more urban areas of Iran which finished "counting" earlier). He began ruling with emergency powers and jailing his opposition. That led to mass resignations in Parliament - to the point where they couldn't even form a quorum. Mosaddegh then dissolved Parliament and granted himself full dictatorial powers and ruled by decree after another sham election where 10% of the population "voted."
And it's at this point that the coup happened. The Shah, using his power under Iran's constitution, wrote a letter dismissing Mosaddegh. He was replaced with Fazlollah Zahedi and the Shah started to take a far more active role in government.
[1] https://history.state.gov/historicaldocuments/frus1951-54Ira...