Molecules in the gas state can be ionized in a variety of ways. These ions hold together sometimes, but fragment at others. The charged ions can be accelerated in an electric field. When the moving ions move through a magnetic field, they are separated on the basis of their charge to mass ratio: the paths of lighter ions bend more in the field.
This techniques is so sensitive that it is possible to determine the exact formula of an ion -- for example, CO is distinguished from N2 even though both have nominal masses of 28 amu/molecule.
Because fragmentation patterns and some fragments are extremely well characterized, and because the precise masses lead to formula information, mass spectroscopy can be used as a structure determination tool.
What is mass spectrometry?
Mass Spectroscopy Tutorial.
Introduction to mass spectrometry, including interpretation.