At least 15 others were wounded, CNN reported.
The dead included four U.N. employees, three women civilians and seven militants, said Abdikarim Hussein Guled, the country's interior and national security minister.
One attacker blew himself up at the entrance, said a police officer, while other militants wearing suicide vests entered the compound.
Somali and African Union forces surrounded the buildings and were able to secure the building after a firefight, the AU forces said in a Twitter message.
"Thankfully, the vast majority of our staff are unhurt," Nicholas Kay, the U.N.'s special representative to Somalia, said in a statement, adding, "The United Nations remains determined to stand by the people of Somalia."
U.N. staffers were evacuated while the compound was under siege.
Ben Parker, a spokesman for the U.N. Assistance Mission in Mogadishu, said fighting between the militants, and Somali and African troops lasted about an hour and a half.
Al-Shabaab claimed responsibility for the attack.
The group, which has links to al-Qaida, opposes the Somali government and the African Union Mission for Somalia, the website African Review said.
Ambassador Mahamat Saleh Annadif, the special representative of the leader of the African Union Commission for Somalia, called the attack "cowardly."
"These futile attacks by al-Shabaab are only aimed at disrupting the ongoing efforts by the Somali people to recover from years of violence in Somalia and will not deter our collective efforts to continue supporting the people of Somalia rebuild their country," he said.
The compound houses the U.N. World Food Program, UNESCO and UNICEF.