Previous diskdrives were sata. A special connector AND protocol to talk to mechanical drives.
The first SSDs used this as well. But quickly they were becoming limited by the sata bus and by the protocol.
So, the m2 ‘format’ (connector and format in one) was borrowed from the laptop world, to plug an ssd directly into the pci-express bus. There is now less protocol conversion and the ssd doesn’t has to bother with pretending to be a mechanical harddrive, which speeds things up. Also massive more bandwidth available :).
The first m2 connectors were ‘a bit fake’, a crossover. They only supported sata SSDs but in a m2 form factor. So they were m2 cards but still talked the sata protocol. And so you also may encounter m2 slots that only support the sata protocol.
These days most m2 slots on a motherboard are directly linked to pci-express lanes on the cpu, providing a direct link to the cpu bandwidth.
Some motherboards have multiple m2 slots. Then one or two might be pci-express, the others still sata. So one for a quick (multiple GigaBYTES per second) boot or system drive, and maybe a cheaper ‘slower’ sata ssd (550mb/sec) for mass storage.
Ssd in m2 format that talks directly over a pci-express bus without sata being involved, is called NVMe. The m2 format (its a card, so format and connector in one) and a raw protocol to talk over the pci-express bus.
The m2 slot is a sort of pci-express slot but smaller, mostly meant for things like wifi and Bluetooth cards in laptops.
A m2 device can have a predefined length, and a motherboard may specify what the maximum length is that fits. The number you see next to m2 (2242, 2260, 2280…) is an indication of physical size. 22mm width, 80mm length for example.
There might be cases where a high speed drive has nand chips on both sides of the m2 device, and maybe even big heatsinks for cooling on one or two sides. You might run into compatibility issues here if that just won’t fit, but on normal motherboards this shouldn’t be an issue.
(in laptops you might encounter that you have a m2 2280 slot, but it’s so cramped only single sided cards are going to fit in there. Or you get weird small slots like m2 2232 or 2240). This is something to double check, but in the desktop world is hardly ever an issue.