The detailed story is mentioned in Mahabharata: Anusasana Parva:
Once on a time as the gods and Danavas were fighting each other in the dark, Rahu pierced both Surya and Soma with his arrows. The gods, overwhelmed by darkness, began to fall before the mighty Danavas, O foremost of kings! Repeatedly struck by the Asuras, the denizens of heaven began to lose their strength.
They then beheld the learned Brahmana Atri, endued with wealth of penances, engaged in the observance of austerities. Addressing that Rishi who had conquered all his senses and in whom wrath had been extinguished, they said 'Behold, O Rishi, these two, viz., Soma and Surya, who have both been pierced by the Asuras with their arrows! In consequence of this, darkness has overtaken us, and we are being struck down by the foe. We do not see the end of our troubles! Do thou, O lord of great puissance, rescue us from this great fear.'
"The Rishi said, 'How, indeed, shall I protect you? They answered, saying, 'Do thou thyself become Chandramas. Do thou also become the sun, and do thou begin to slay these robbers!'
Thus solicited by them, Atri assumed the form of the darkness-destroying Soma. Indeed, in consequence of his agreeable disposition, he began to look as handsome and delightful as Soma himself. Beholding that the real Soma and the real Surya had become darkened by the shafts of the foe, Atri, assuming the forms of those luminaries, began to shine forth in splendour over the field of battle, aided by the puissance of his penances. Verily Atri made the universe blaze forth in light, dispelling all its darkness. By putting forth his puissance, he also subjugated the vast multitudes of those enemies of the deities. Beholding those great Asuras burnt by Atri, the gods also, protected by Atri's energy, began to despatch them quickly. Putting forth his prowess and mastering all his energy, it was even in this way that Atri illumined the god of day, rescued the deities, and slew the Asuras!