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

86
Views
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 answers
Answer question

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 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!