Postoperative cognitive dysfunction (POCD) affects the outcome of millions of patients each year. Aging is a risk factor for POCD. Here, we showed that surgery induced learning and memory dysfunction in adult mice. Transplantation of feces from surgery mice but not from control mice led to learning and memory impairment in non-surgery mice. Low intensity exercise improved learning and memory in surgery mice. Exercise attenuated surgery-induced neuroinflammation and decrease of gut microbiota diversity. These exercise effects were present in non-exercise mice receiving feces from exercise mice. Exercise reduced valeric acid, a gut microbiota product, in the blood. Valeric acid worsened neuroinflammation, learning and memory in exercise mice with surgery. The downstream effects of exercise included attenuating growth factor decrease, maintaining astrocytes in the A2 phenotypical form possibly via decreasing C3 signaling and improving neuroplasticity. Similar to these results from adult mice, exercise attenuated learning and memory impairment in old mice with surgery. Old mice receiving feces from old exercise mice had better learning and memory than those receiving control old mouse feces. Surgery increased blood valeric acid. Valeric acid blocked exercise effects on learning and memory in old surgery mice. Exercise stabilized gut microbiota, reduced neuroinflammation, attenuated growth factor decrease and preserved neuroplasticity in old mice with surgery. These results provide direct evidence that gut microbiota alteration contributes to POCD development. Valeric acid is a mediator for this effect and a potential target for brain health. Low intensity exercise stabilizes gut microbiota in the presence of insult, such as surgery.