HexaCrop
HexaCrop

Reputation: 4263

mongoose sort, limit and then distinct

I have a model Model in mongoose, where there are 3 fields. data, main_id and sub_id

So if I do Model.find():

I get something like below

[
 {data: 5, main_id: A, sub_id: X, created: 5/4/2020}, 
 {data: 6, main_id: A, sub_id: Y, created: 5/4/2020}, 
 {data: 7, main_id: B: sub_id: M, created: 4/4/2020}, 
 {data:11, main_id: A, sub_id: X, created: 3/4/2020}, 
 {data:12, main_id: A, sub_id: Y, created: 4/4/2020}, 
 {data:13, main_id: A, sub_id: X, created: 4/4/2020}
]

I want to get all the data field that is unique to main_id: A sorted by created and limit to 1 for each sub_id under the main_id

So, in this case, I want to have a returned array of [5, 6] because that is the latest data entry for main_id: A and latest for sub_id: X and Y which are under main_id: A respectively.

Upvotes: 0

Views: 74

Answers (1)

SuleymanSah
SuleymanSah

Reputation: 17858

You can achieve this using $match, $sort and $group aggregations stages.

Model.aggregate([
  {
    $match: {
      "main_id": "A"
    }
  },
  {
    $sort: {
      "created": -1
    }
  },
  {
    $group: {
      "_id": {sub_id: "$sub_id"},
      data: {
        "$first": "$data"
      }
    }
  }
])

Playground

The result:

[
  {
    "_id": "Y",
    "data": 6
  },
  {
    "_id": "X",
    "data": 5
  }
]

Note that .aggregate() method always returns objects, so in express application you can do a simply map to transform it to [5, 6].

Upvotes: 1

Related Questions