Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

256
Views
Mongo DB + grupo por con datos del último campo

Tengo datos json de muestra en colecciones.

Data de muestra:

 [{ "_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") }]

Estos datos que necesito para recuperar datos para las siguientes condiciones.

  1. Agrupar por nombre de usuario.
  2. nombre de usuario no es igual a "zzz"
  3. Ordenar por fecha desc orden.
  4. también necesita el campo de fecha (que tiene el último/último registro).
  5. obtener el recuento total.

Esperando salida:

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

Consulta:

 db.logs.aggregate([ { "$match": { "username": { "$ne": "zzz" } }}, { "$group": { "_id": { "username": "$username", "createdDate": "$createdDate" }, "count": { "$sum": 1 } }}])
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

prueba esto :

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

producción

 { "_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") }

Pruébelo en línea: mongoplayground.net/p/3_-s2tUjPFi

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!