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

118
Views
Mongodb find multiple and retrive one record for matching id

I'm trying to find many records in the same query, the records are of this type

{
    "key": 2,
    time: 3
  },
  {
    "key": 2,
    time: 5
  },
  {
    "key": 3,
    time: 4
  }

I'd like to retrive for example the records with key inside [2,3] and with the relative maximum amount of time, so in this case recrods with { "key": 2, time: 5 } and { "key": 3, time: 4 } should be returned.

So far i got only how to retrive the records with key inside in a proveded array but i'm not understanding how to get for each key in the array the record with the latest time, i'd like to not use the where operator.

Here is a playground with the provided scenario https://mongoplayground.net/p/5sWnn8_HnqK

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

You can use aggregate function to find max element for each key. Example: https://mongoplayground.net/p/P9JSuvTHdZa

    db.collection.aggregate([
  {
    $match: {
      key: {
        $in: [
          2,
          3
        ]
      }
    }
  },
  {
    $group: {
      _id: "$key",
      time: {
        $max: "$time"
      }
    }
  }
])

Edited: as in comment suggested

over 4 years ago · Santiago Trujillo Report

0

The easiest way to achieve this is by matching the documents, sorting them descendingly and then choose the "first" document for each key, like so:

db.collection.aggregate([
  {
    $match: {
      key: {
        $in: [
          1,
          2,
          3
        ]
      }
    }
  },
  {
    $sort: {
      time: -1
    }
  },
  {
    $group: {
      _id: "$key",
      first: {
        $first: "$$ROOT"
      }
    }
  }
])
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!