I'm unsure the level which this question is being asked, but hopefully this answers your question.
As you pointed out "why did Oxygen take 2 electrons from magnesium" well if you would allow me to be rather 'hand-wavy' about the whole thing the reason is due to a activation energy vs ionization energy and bond-dissociation energy.
If you stick some fresh magnesium in an oxygen rich environment it won't all spontaneously react. This is because there is an amount of energy required for the reaction to happen (I will refer to this as activation energy). Now to make the reaction between magnesium and oxygen gas happen two things need to happen, the magnesium needs to lose two of its electrons (ionization energy) and the oxygen needs to break into two individual oxygen atoms(bond-dissociation energy). The misconception here is that oxygen gas will split into two -2 ions. If you count the number of electrons in one molecule of oxygen gas you get 12 electrons. Two -2 oxygen ions come out to total 16 electrons.
In reality, O2 would split into two neutral oxygen atoms as the oxygen gas is a neutral species not an ion. This is obviously incredibly unstable which is why it will look for the nearest source of electrons to pull from and magnesium's electrons are relatively easy to grab vs the oxygen. Reply if you want any more detail on anything I've said so far (as a lot of it is rather hand-wavy on my end), but if this is for a intro chemistry class I don't want to overload you with more information than you need.