Mongoose return 10 results sorted by date for every user id in array of ids

Viewed 170

lets say we have an array of user ids :

    "ids": [
        "623d71c628820d09797be558",
        "62419d6477775214de099838",
        "62419d7877775214de099845",
        "62419d8877775214de09984c"
    ]

and we want to return the first 10 documents of every id sorted by date. I know we can do :

  const docs = await Model.find({ id: { $in: ids } })
    .sort("date")
    .limit(10);

which returns 10 documents sorted by date,but not for every user,how could i return 10 for every one in array ?

** EDIT **

Here's an example document from the balance collection:

  {
    "_id": "624a19a0b1cf7d69a5193737",
    "user": {
      "name": "john",
      "id": "623d71c628820d09797be558"
    },
    "description": "chips",
    "amount": 2,
    "type": "expense",
    "date": "2022-04-03T22:03:12.774Z",
    "__v": 0
  }

and a "user" document :

{
        "_id": "623d71c628820d09797be558",
        "name": "john",
        "__v": 0
}
1 Answers

Here's one way you could do it using an aggregation pipeline.

db.collection.aggregate([
  {
    "$match": {
      "id": {
        "$in": [
          "623d71c628820d09797be558",
          "62419d6477775214de099838",
          "62419d7877775214de099845",
          "62419d8877775214de09984c"
        ]
      }
    }
  },
  {
    "$sort": { "date": 1 }
  },
  {
    "$group": {
      "_id": "$id",
      "docs": { "$push": "$$CURRENT" }
    }
  },
  {
    "$project": {
      "_id": 0,
      "id": "$_id",
      "docs": { "$slice": [ "$docs", 10 ] }
    }
  }
])

Try it on mongoplayground.net.

Related