The order required the immediate release of Gens. Ricardo Escorcia Vargas, a former deputy defense secretary, Ruben Perez Ramirez and Roberto Dawe Gonzalez, Col. Silvio Isidro de Jesus Hernandez Soto and Maj. Ivan Reyna Munoz, the newspaper Excelsior reported. All were arrested last year while Felipe Calderon was president and accused of working with the Beltran Leyva cartel.
The attorney general's office told the court it had decided against trying the military officers. It had concluded testimony against them was false.
Retired Gen. Tomas Angeles Dauahare was freed in April.
Calderon, who served as president from 2006 to 2012, launched an aggressive drug policy aimed at the cartels and depending heavily on the military, which was generally seen as less corrupt than the police. The policy was successful at killing or imprisoning many cartel leaders, but critics say it led to increased drug violence.
One of the four Beltran Leyva brothers was killed in 2009, two are in prison and the fourth is a fugitive.