Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
MongoDB Aggregate Query, Logins Averages
let pipeline = [{
    $match: {
        time: { $gt: 980985600 },
        user_id: mongoose.Types.ObjectId("60316a2e7641bd0017ced7b1")
    }
},
{
    $project: {
        newDate: { '$toDate': "$time" },
        user_id: '$user_id'
    }
},
{
    $group: {
        _id: { week: { $week: "$newDate" }, year: { $year: "$newDate" }},
        count: { $sum: 1 }
    }
}]

I am currently trying to perform an aggregate through mongoose to find the average logins per week for a specific user. So far I have been able to get to the total number of logins each week, but was curious if there was a way to find the average of these final groupings within the same function. How would I go about doing this?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Just add one last stage to your query:

{
    $group: {
        _id: null,
        avg: { $avg: "$count" }
    }
}

So try this:

let pipeline = [
    {
        $match: {
            time: { $gt: 980985600 },
            user_id: mongoose.Types.ObjectId("60316a2e7641bd0017ced7b1")
        }
    },
    {
        $project: {
            newDate: { '$toDate': "$time" },
            user_id: '$user_id'
        }
    },
    {
        $group: {
            _id: { week: { $week: "$newDate" }, year: { $year: "$newDate" } },
            count: { $sum: 1 }
        }
    },
    {
        $group: {
            _id: null,
            avg: { $avg: "$count" }
        }
    }
];
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda