Counting objects in a collection
MongoDB: Here’s a small script to count some values in a collection.
What can’t you do with Python? I really like statistics, especially my own.
For my MongoDB database, which I use to track more data on Spain than MariaDB, I’ve written a small script to collect a lot of average values. With 521 documents, it’s interesting to know these averages.
Here is a screenshot with the current results:

And here’s the script:
import pymongo
def generar_estadisticas():
try:
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["Laender"]
collection = db["Espana"]
print("\n📊 Estadísticas de ciudades en España:")
# 1. Total de entradas (Usando count_documents)
total_ciudades = collection.count_documents({})
# Hilfsfunktion für Aggregationen, um Code-Wiederholung zu vermeiden
def get_avg(field):
pipeline = [{"$group": {"_id": None, "avgValue": {"$avg": f"${field}"}}}]
res = list(collection.aggregate(pipeline))
return res[0]['avgValue'] if res else 0
# Durchschnittswerte berechnen
avg_altitud = get_avg("Altitud")
avg_superficie = get_avg("Superficie")
avg_poblacion = get_avg("Poplación") # Achtung: Prüfe, ob es "Población" oder "Poplación" (wie in deinem aggregate-Output vorhin) heißt!
print(f"Total de entradas: {total_ciudades}")
print(f"Promedio Altitud: {avg_altitud:.2f} m")
print(f"Promedio Superficie: {avg_superficie:.2f} km²")
print(f"Promedio Población: {avg_poblacion:.0f} habitantes")
client.close()
except Exception as e:
print(f"❌ Error: {e}")
generar_estadisticas()