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

268
Vistas
Mongo DB + group by with last field data

I have sample json data in collections.

Sample data:

[{
    "_id" : 1,
    "username" : "abcd",
    "createdDate" : ISODate("2016-06-03T08:52:32.434Z")
},
{
    "_id" : 2,
    "username" : "abcd",
    "createdDate" : ISODate("2016-05-03T09:52:32.434Z")
},
{
    "_id" : 3,
    "username" : "abcd",
    "createdDate" : ISODate("2016-04-03T10:52:32.434Z")
},
{
    "_id" : 4,
    "username" : "xyz",
    "createdDate" : ISODate("2016-03-03T10:52:32.434Z")
},{
    "_id" : 5,
    "username" : "xyz",
    "createdDate" : ISODate("2016-02-03T10:52:32.434Z")
},{
    "_id" : 6,
    "username" : "zzz",
    "createdDate" : ISODate("2016-01-03T10:52:32.434Z")
}]

This data I need to retrieve data for following condtions.

  1. Group by username.
  2. username not equal "zzz"
  3. Order by date desc order.
  4. need date field also (which have lastest/last record).
  5. get total count.

Expecting output:

[{
    "username" : "abcd",
    "createdDate" : "2016-06-03T08:52:32.434Z",
        "total" : 3
},
{
    "username" : "xyz",
    "createdDate" : "2016-03-03T10:52:32.434Z",
        "total" : 2
}]

Query:

db.logs.aggregate([
    { "$match": { "username": { "$ne": "zzz" } }},

    { "$group": {
        "_id": {
            "username": "$username",
            "createdDate": "$createdDate"
        },
        "count": { "$sum": 1 }
    }}])
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

try this :

    db.logs.aggregate([
   {
      "$match":{
         "username":{
            "$ne":"zzz"
         }
      }
   },
   {
      "$group":{
         _id:"$username",
         "count":{
            "$sum":1
         },
         date:{
            $max:"$createdDate"
         }
      }
   },
   {
      $project:{
         username:"$_id",
         total:"$count",
         createdDate:"$date"
      }
   }
])

output

  {
   "_id":"xyz",
   "username":"xyz",
   "total":2,
   "createdDate":   ISODate("2016-03-03T10:52:32.434   Z")
}{
   "_id":"abcd",
   "username":"abcd",
   "total":3,
   "createdDate":   ISODate("2016-06-03T08:52:32.434   Z")
}

try it online: mongoplayground.net/p/3_-s2tUjPFi

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