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

122
Vistas
Multiple Groupings for MongoDB Aggregate

Given the following data set of Event objects:

[
    {
        "_id": ObjectId("4fda05cb322b1c95b531ac26",
        "title": "BUTTON CLICKED",
        "createdAt": ISODate("2017-01-12T01:00:00+01:00")
    },
    {
        "_id": ObjectId("1235h1k235h1kl325h1v31gv",
        "title": "BUTTON CLICKED",
        "createdAt": ISODate("2017-01-14T01:00:00+01:00")
    },
    {
        "_id": ObjectId("c2n890904cn897qnxp23hjk1",
        "title": "PAGE VIEWED",
        "createdAt": ISODate("2017-01-12T02:00:00+01:00")
    }
]

How would I group them by date then by name?

The desired result would look like this:

[ 
  { 
    _id: { year: 2017, month: 1, day: 11 },
    events: [ { 
                title: "BUTTON PRESSED",
                count: 3
               }, { 
                title: "PAGE VIEWED",
                count: 2
               }
            ] 
  },
  { 
    _id: { year: 2017, month: 1, day: 24 },
    events: [ { 
                title: "BUTTON PRESSED",
                count: 1
               }
            ] 
  }
]

Any help on this issue would be greatly appreciated, so thank you!

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

0

you can try this query

db.collectionName.aggregate([
    $group: {
       _id : {
        year : { $year : "$createdAt" },
        month : { $month : "$createdAt" },
        day : { $dayOfMonth : "$createdAt" },
        title: "$title"
       },
       count:{$sum:1}
      }
    },
  {
    $group:{
      _id:{
        year: "$_id.year",
        month: "$_id.month",
        day: "$_id.day"
      },
      data:{
        $push: {
          name:"$_id.title",
          count:"$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