Search code examples
mongodbmongooseaggregation

Mongo aggregations with multiple different sorts


So I'm kind of new to Mongo aggregations and after a lot of researching and googling I can't figure out how to do a particular query.

Say I have many documents with the following format:

{
  _id: 1,
  client: "Some Client",
  type: "Some Type",
  firstUsed: 2021-01-05T13:23:37.000+0000
  lastUsed: 2021-05-05T18:11:23.000+0000
}

What I'm trying to do is group all the documents by type (for a particular client), and then get the first firstUsed datetime and the last lastUsed datetime.

I've been playing with aggregations but after doing a $match on the client, $group on the type, I can only figure out then how to get only one of the dates I need.

Sorting by firstUsed and getting the first document is fine, but then getting the last document doesnt mean I'm getting the correct lastUsed.

How do I re-sort and get the last lastUsed datetime while keeping the already found firstUsed?

Hope that makes sense,

Thanks


Solution

  • From what you said I think you are trying to get the earliest first date and the greatest last data. You can use $max and $min for the dates. Here's a solution that you can use:

    {
    $group: {
      _id: "$type",
      firstUsed: {
        $min: "$firstUsed"
      },
      lastUsed: {
        $max: "$lastUsed"
      }, 
     }
    }
    

    https://mongoplayground.net/p/v-QK2ItL3uq