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

88
Vistas
Including additional fields in a Mongodb aggregate query

I have a data structure like this. Each student will have multiple entries based on when they enter the classrooms. The query needs to get the latest record of each student based on a list of student ids and department name. It also should show the teacher id and last timestmap

[
  {
    "studentid": "stu-1234",
    "dept": "geog",
    "teacher_id": 1,
    "LastSwipeTimestamp": "2021-11-25T10:50:00.5230694Z"
  },
  {
    "studentid": "stu-1234",
    "dept": "geog",
    "teacher_id": 2,
    "LastSwipeTimestamp": "2021-11-25T11:50:00.5230694Z"
  },
  {
    "studentid": "stu-abc",
    "dept": "geog",
    "teacher_id": 11,
    "LastSwipeTimestamp": "2021-11-25T09:15:00.5230694Z"
  },
  {
    "studentid": "stu-abc",
    "dept": "geog",
    "teacher_id": 21,
    "LastSwipeTimestamp": "2021-11-25T11:30:00.5230694Z"
  }
]

Here is what I have, but it doesn't show teacher id or the last swipe timestamp. What do I need to change or add?

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

0

Maybe you need something like this

db.collection.aggregate([
  {
    $match: {
  "studentid": {
    "$in": [
      "stu-abc",
      "stu-1234"
    ]
     },
  "dept": "geog"
    }
  },
  {
    $sort: {
      "LastSwipeTimestamp": -1
    }
  },
  {
    $group: {
      "_id": {
        "studentid": "$studentid",
        "dept": "$dept"
      },
      "teacher_id": {
        $first: "$teacher_id"
      },
      "LastSwipeTimestamp": {
        $first: "$LastSwipeTimestamp"
      }
    }
  },
  {
    $project: {
      _id: 0,
      "studentid": "$_id.studentid",
      "dept": "$_id.dept",
      "teacher_id": "$teacher_id",
     "LastSwipeTimestamp": "$LastSwipeTimestamp"
    }
  }
 ])

explained: You need to consider the not grouped fields in the $group stage so they are also available to the next $project stage...

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