The decisive moment arrived four minutes into the second half when the visitors broke quickly with Henri Anier providing the assist for Ainsworth who found the back of the net with a strike into the bottom right-hand corner.
The goal had come against the run of play and, as Aberdeen chased an equaliser, Joe Shaughnessy struck the right-hand post with a left-foot volley from outside the box.
Peter Pawlett went close with an 89th minute header and, with 93 minutes on the clock, Neil McGinn struck a free-kick that flew wide of the right post and into the side-netting.
In a goalless first half, Aberdeen dominated possession and also created the majority of the chances.
McGinn went close twice, while Jonathan Hayes and Pawlett flashed headers narrowly wide during the opening 45 minutes.