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

164
Vistas
Group by months and get their counts in MongoDB

I have a document with the following structure.

{
    "_id" : ObjectId(""),
    "review_id" : "1",
    "product_id" : "1",
    "date" : 1638869377,
    "rating" : 5,
    "title" : "lorem",
    "review" : "lorem",
    "updated_at" : ISODate("2021-12-07T07:10:55.732Z"),
    "created_at" : ISODate("2021-12-07T05:04:11.750Z")
}

I managed to get the number of user comments by month. But I want to get it separately for each rating.

For example, in the 10th month there are 7 comments and how can I get 2 of them 1 star, 3 of them 4 stars, 2 of them 5 stars?

 {
  "$group": {
    "_id": {
      "month": {
        "$month": {
          "$toDate": "$date"
        }
      }
    },
    "reviews": {
      "$sum": 1
    }
  }
}
over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

You just want to $group by both fields, the month and the rating, like so:

db.collection.aggregate([
  {
    "$group": {
      "_id": {
        "month": {
          "$month": {
            "$toDate": "$date"
          }
        },
        rating: "$rating"
      },
      "reviews": {
        "$sum": 1
      }
    }
  }
])

Mongo Playground

Or my recommendation just to add a little more structuring to the output is to use this pipeline.

over 4 years ago · Santiago Trujillo Denunciar

0

You could add everything you want to group by inside the _id field. Just adding a new field with the rating would do the job.

{
  "$group": {
    "_id": {
      "month": {
        "$month": {
          "$toDate": "$date"
        }
      },
      "rating": "$rating"
    },
    "reviews": {
      "$sum": 1
    }
  }
}

Note: I would also add a group by year, so you can get each month separed properly. If you dont add them, Mongo will group every January of every year together for example.

Playground

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