Answer:
If you look at the periodic table, magnesium (Mg) is in group 2, meaning it has 2 electrons on it's outer shell.
Oxygen (O) is in group 6, meaning it has 6 electrons in its outer shell.
To form an ionic bonds, both elements need to have full outer shells/ 8 electrons in their outer shell.
Oxygen only needs 2 electrons to become an ion, and magnesium is able to give 2 away, so oxygen takes 2 from magnesium to form an ionic bond.