Brazil striker Richarlison, who netted a hat-trick against Germany in their opener, headed in to make it 2-1 before tucking away his fifth goal at the Games to seal all three points at the Saitama Stadium and set up a quarter-final meeting with Egypt
Defending champions Brazil advanced to the quarter-finals of the men's Olympic soccer tournament after a 3-1 victory over Saudi Arabia on Wednesday helped them top Group D while Ivory Coast booked their berth by sending Germany home.
Japan advanced after delivering the knockout blow to 10-man France with a 4-0 win to stay perfect in Group A. Takefusa Kubo, Hiroki Sakai, Koji Miyoshi and Daizen Maeda all scored for the rampant hosts while Randal Kolo Muani was sent off for France.
They take on New Zealand in the quarter-finals while Mexico, who pipped France to second place in Group A with a 3-0 win over South Africa, will meet South Korea.
Brazil striker Richarlison, who netted a hat-trick against Germany in their opener, headed in to make it 2-1 before tucking away his fifth goal at the Games to seal all three points at the Saitama Stadium and set up a quarter-final meeting with Egypt.
The South Americans needed only 14 minutes to take the lead as forward Matheus Cunha nodded the ball past goalkeeper Amin Albukhari from Claudinho's corner but Saudi Arabia made it 1-1 through defender Abdulelah Alamri's header from a free kick.
Brazil, without the firepower of Neymar and Gabriel Jesus from the 2016 Games, scored four against Germany but struggled to fire in a goalless draw against Ivory Coast and their inconsistency was on display again.
Guilherme Arana, Diego Carlos and Antony failed to put away first-half chances and Cunha hit the post after the break, as already-eliminated Saudi Arabia frustrated Brazil before Richarlison's brace.
Spain progressed as Group C winners after a 1-1 draw with Argentina as Mikel Merino's second-half goal was cancelled out by Tomas Belmonte with three minutes to go.
Egypt joined them after a 2-0 victory over Australia lifted the African side to second in the group above Argentina on goal difference.
Ivory Coast went through at the expense of Germany, securing a 1-1 draw with the 2016 silver medallists at Miyagi Stadium.
The African side took the lead in the 67th minute when Benjamin Henrichs attempted to make a tackle in the six-yard box and ended up putting the ball into his own net but substitute Eduard Loewen scored with a free kick six minutes later.
Germany piled on the pressure in the dying stages but Ivory Coast held on to finish second in the group and set up a meeting with Spain.
South Korea forward Hwang Ui-jo scored a hat-trick as they thrashed Honduras 6-0 while New Zealand went through after their goalless draw with Romania.