'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:

{
    "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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source