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: find documents but drop duplicates by key

What I want is to find documents but dropping duplicates by some key, retrieving only the updated document (by a date field)

So for this collection:

{
    "key": "a", 
    "time": ISODate("2021-10-20T00:00:00.000Z")
},
{
    "key": "a",
    "time": ISODate("2020-10-20T00:00:00.000Z")
},
{
    "key": "b",
    "time": ISODate("2020-10-20T00:00:00.000Z")
},
{
    "key": "b",
    "time": ISODate("2019-10-20T00:00:00.000Z")
}

We will get the following docs:

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

{
    "key": "a",
    "time": ISODate("2021-10-20T00:00:00.000Z")
},
{
    "key": "b",
    "time": ISODate("2020-10-20T00:00:00.000Z")
}

How can I do that?

>Solution :

  1. $sort – Order the documents by key ASC and time DESC.
  2. $group – Group by key and take the first document as data.
  3. $replaceWith – Decorate output document with data.
db.collection.aggregate([
  {
    "$sort": {
      "key": 1,
      "time": -1
    }
  },
  {
    $group: {
      _id: "$key",
      "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