Ludwig Augustinsson scored in the 50th minute, past Mexico's goalkeeper Ocho, then a penalty allowed captain Andreas Granqvist to put a second goal in the Mexican net after 62 minutes.
Mexico made an own goal after 74 minutes.
The tense match had already seen a yellow card for Mexico in the first few seconds, and minutes later Marcus Berg was close to scoring.
Sweden got their own warning, after 25 minutes that had seen both teams have good chances at goals.
In the 56th minute Sebastian Larsson had to be stretchered off the pitch.
Sweden's men's team failed to even qualify for the last two World Cups, but made the knockout stage in 2002 and 2006. They have yet to beat their top result of bronze in 1994.
Wednesday's win means Sweden exits as the top team from Group F, while defending world champions Germany have failed to qualify from the group, after being beaten by South Korea.
Sweden will now face Brazil, Switzerland or Serbia in their next match, in the knockout stage.