The Messenger of Allah ﷺ arrived in Madinah and stayed in the upper part of the city among a clan called Banu Amr bin Awf. He remained with them for fourteen nights, then he sent for Banu Najjar, who came wearing their swords.Anas said, "It is as though I can still see the Messenger of Allah ﷺ on his mount, with Abu Bakr riding behind him and the men of Banu Najjar gathered around him, until he dismounted in the courtyard of Abu Ayub."The Messenger of Allah ﷺ used to pray wherever the time of prayer overtook him, even in the resting places of sheep. Then he ordered that a mosque be built. He sent for Banu Najjar and said, "Banu Najjar, name me a price for this orchard of yours."They replied, "By Allah, we will seek its price from no one but Allah ."Anas said, "I will tell you what was in it. It contained graves of polytheists, ruins, and date palms."The Messenger of Allah ﷺ gave orders for the graves of the polytheists to be exhumed, for the ruins to be leveled, and for the date palms to be cut down. They lined up the trunks of the palms as the qiblah of the mosque and set up its doorposts with stones. They began carrying the stones, chanting verses, and the Prophet ﷺ was with them, saying, "Allah, there is no good except the good of the Hereafter, so grant victory to the Ansar and the Muhajirin."
حدثنا مسدد حدثنا عبد الوارث عن أبي التياح
قدم رسول الله ﷺ المدينة فنزل في علو المدينة في حي يقال لهم بنو عمرو بن عوف فأقام فيهم أربع عشرة ليلة ثم أرسل إلى بني النجار فجاءوا متقلدين سيوفهم فقال أنس فكأني أنظر إلى رسول الله ﷺ على راحلته وأبو بكر ردفه وملأ بني النجار حوله حتى ألقى بفناء أبي أيوب وكان رسول الله ﷺ يصلي حيث أدركته الصلاة ويصلي في مرابض الغنم وإنه أمر ببناء المسجد فأرسل إلى بني النجار فقال يا بني النجار ثامنوني بحائطكم هذا فقالوا والله لا نطلب ثمنه إلا إلى الله عز وجل قال أنس وكان فيه ما أقول لكم كانت فيه قبور المشركين وكانت فيه خرب وكان فيه نخل فأمر رسول الله ﷺ بقبور المشركين فنبشت وبالخرب فسويت وبالنخل فقطع فصفوا النخل قبلة المسجد وجعلوا عضادتيه حجارة وجعلوا ينقلون الصخر وهم يرتجزون والنبي ﷺ معهم وهو يقول اللهم لا خير إلا خير الآخره فانصر الأنصار والمهاجره
Bukhari narrated it in the chapter on prayer, in the section "Should the graves of the polytheists of the pre-Islamic era be dug up and their site used as masjids", hadith 428, from Musaddad. Muslim narrated it in the chapter on masjids, in the section on building the masjid of the Prophet, hadith 524, from the hadith of Abdul-Warith bin Saeed, through the same chain.