Dack came closest for his team in the first half when his flick bounced back off the post with Myles Weston lurking after 15 minutes.
Notts wanted a penalty when McGregor's shot was blocked inside the area, but the referee waved away the appeals on 37 minutes.
However, McGregor had the ball in net three minutes later when he drilled it low beyond Stuart Nelson in the Gillingham goal.
Gillingham equalised three minutes after the restart when Dack reacted quickest from a long-throw to bundle it home.
Notts regained the lead eight minutes later when McGregor put a lovely finish on the home side's move.
Grealish added a late effort to make the result secure for Sean Derry's side.
Despite the win, Derry's side are still bottom of League One.