Rafa Mir struck a hat-trick off the bench as Spain booked their place in the semifinals of the Olympic Games with a 5-2 win against Ivory Coast after extra time.
Eric Bailly opened the scoring in the 10th minute but the sides went in level at half-time thanks to Dani Olmo's effort.
The game was heading to extra-time when Max Gradel appeared to have won it for Ivory Coast in the 91st minute, only for a dramatic finale to unfold in Miyagi.
Substitute Mir, sent on in stoppage time, took advantage of some sloppy defending to score with his first touch of the match and take the tie into an additional 30 minutes.
Bailly's handball then gave Spain the chance to take the lead from the penalty spot, with Real Sociedad's Mikel Oyarzabal making no mistake in the 98th minute.
With Ivory Coast tired and chasing a leveller for penalties, Mir took full advantage at the other end to seal the game for Spain.
The Wolverhampton Wanderers striker scored twice in the final three minutes to book La Roja's place in the final four and keep their Gold medal hopes alive.