How to programmatically set a menu to be the Primary Menu?

I dug through the wordpress code to see what was happening when I submitted the form from the admin UI to see what function it was calling (and did a var_export() on the variable being passed in) and saw it was calling set_theme_mod( 'nav_menu_locations', $menu_locations );. I’ve updated my code to use this and it seems to be working:

$locations = get_theme_mod('nav_menu_locations');
$locations['primary'] = $menu_id;
set_theme_mod( 'nav_menu_locations', $locations );

One of the things that threw me off when I was trying to figure out how to do this is that the documentation for get_theme_mod() says that it returns a string, but in this case it is returning an array and so I didn’t think it was going to work.