How to choose and download the most stable structure with the lowest formation energy?

hi, everyone, for a formula with multiple reported formation energies,how to choose and download the most stable structure with the lowest formation energy?How to write a query statement ?
I’ll be very thankful for any suggestions

Since finding the entry with the lowest formation energy for a given formula involves an “aggregation” operation (see MongoDB aggregation) it is probably easiest to do this by sorting a list of entries you’ve already queried for a given formula.

In the Python example below, entries are obtained from the Materials Project using MPRester, then we use sorted() to sort by energy per atom and take the first element of the sorted list. Note that we can use the energy_per_atom property instead of the actual formation energy since we’re dealing with entries all of the same chemical formula.

from pymatgen.ext.matproj import MPRester

formula = ""  # FILL IN desired formula between quotes

with MPRester() as mpr:
    entries = mpr.get_entries(formula)

min_entry = sorted(entries, key=lambda e: e.energy_per_atom)[0]