Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

156
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda