Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

MongoDB query: Find multiple first matching document

I have a collection with the following schema:

{
  _id: ObjectId,
  company: ObjectId,
  endTime: date string
}

There will be multiple documents for the same company.
Few example docs:

{_id: 1, company: companyA, endTime: Jan 1,2022}
{_id: 2, company: companyB, endTime: Feb 11,2022}
{_id: 3, company: companyA, endTime: Jan 3,2022}
{_id: 4, company: companyB, endTime: Jan 4,2022}
{_id: 5, company: companyA, endTime: Feb 21,2022}
{_id: 5, company: companyB, endTime: Jan 1,2022}

Now I want to get the first document per company sorted by endTime (desc). I tried with aggregate but was not able to accomplish it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Result for above docs:

{_id: 5, company: companyA, endTime: Feb 21,2022}
{_id: 2, company: companyB, endTime: Feb 11,2022}

Any help would be appreciated.

>Solution :

  1. $sort – Sort by endTime DESC.
  2. $group – Group by company and take first document ($first) as data field.
  3. $replaceWith – Replace the input document with data.
db.collection.aggregate([
  {
    $sort: {
      endTime: -1
    }
  },
  {
    $group: {
      _id: "$company",
      data: {
        $first: "$$ROOT"
      }
    }
  },
  {
    "$replaceWith": "$data"
  }
])

Sample Mongo Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading