I'm looking at XTR Di2, and it seems the rear derailleur comes in 2 variations: medium cage and long cage. What are the two sizes for? Do they match different types of cassettes? What kind would I need for an 11-42 or 11-46?
A long cage is used for drivetrains with a wide range. A wide range would be a typical triple front crank or a wide ratio cassette (11-46 tooth) with a double crank. To determine what you need you need to determine the tooth capacity of the derailleur (check Shimano web site for tech information). Add the difference of the cassette tooth count (42-11=31) crankset(36-26=10) for a total tooth count of 41. You may be thinking that a long cage would always be a better choice for the flexibility of range. However the long cage can be an issue for a mountain bike where logs, rocks and such love the big target of the long cage. This is especially important with 26" wheels where everything is lower to the ground.
Whether you need the long cage SGS or medium cage GS depends on what chainrings you want to run. As @mikes says the the derailleur needs a sufficient total capacity.
The Shimano XTR M9050 line up docs say:
SGS - 41 teeth
GS - 35 teeth
You also need to be aware of the max sprocket size the derailleur will handle. Shimano's specs are:
SGS: 40 (3x11-speed) 42 (2x11-speed) 46 (1x11-speed)
GS: 42 (2x11-speed) 46 (1x11-speed)