0

I have document like this:

{
  "_id": "620b5e8ccc5ea26474efc3b5",
  "title": "B001",
  "garbage": false,
  "content": "This is content...",
  "nom": 0,
  "gmt_create": 1644912268678,
  "gmt_modify": 1644912268678,
  "category_id": "620b5e75cc5ea26474efc3b3"
},
{
  "_id": "620b5e98cc5ea26474efc3b9",
  "title": "B002",
  "garbage": false,
  "content": "This is content...",
  "nom": 6,
  "gmt_create": 1644912280337,
  "gmt_modify": 1645113293348,
  "category_id": "620b5e75cc5ea26474efc3b3"
},
{
  "_id": "620b5e98cc5ea26474ef9a11",
  "title": "C001",
  "garbage": false,
  "content": "This is content...",
  "nom": 2,
  "gmt_create": 1644912280337,
  "gmt_modify": 1645113293348,
  "category_id": "620b5e75cc5ea26474ef0491"
},
{
  "_id": "620b5e98cc5ea26474efee22",
  "title": "D001",
  "garbage": false,
  "content": "This is content...",
  "nom": 1,
  "gmt_create": 1644912280337,
  "gmt_modify": 1645113293348,
  "category_id": "620b5e75cc5ea26474ef9999"
 }

I have an array that contains some category_id:

const cids = ['620b5e75cc5ea26474efc3b3', '620b5e75cc5ea26474ef0491']

I hope I can output like this:

[    
  {
    "category_id": "620b5e75cc5ea26474efc3b3",
    "data": [
      {
        "_id": "620b5e8ccc5ea26474efc3b5",
        "title": "B001",
        "gmt_create": 1644912268678,
        "gmt_modify": 1644912268678,
      },
      {
        "_id": "620b5e98cc5ea26474efc3b9",
        "title": "B002",
        "gmt_create": 1644912280337,
        "gmt_modify": 1645113293348,
      }
    ]
  },
  {
    "category_id": "620b5e75cc5ea26474ef0491",
    "data": [
      {
        "_id": "620b5e98cc5ea26474ef9a11",
        "title": "C001",
        "gmt_create": 1644912280337,
        "gmt_modify": 1645113293348,
      }
    ]
  }
] 

How could I achieve this? Any answer will be appreciated.

chridam
  • 100,957
  • 23
  • 236
  • 235
lai9fox
  • 59
  • 7
  • Have you looked at [mongoose.findOne](https://mongoosejs.com/docs/api.html#model_Model.findOne)? – Tytrox Feb 28 '22 at 17:17
  • Or even [mongoose.findById()](https://mongoosejs.com/docs/api.html#model_Model.findById) – Tytrox Feb 28 '22 at 17:18
  • Similar to the marked answer in the duplicate, your aggregation pipeline should be something like `Model.aggregate([{$match:{category_id:{$in: cids.map(c=>mongoose.Types.ObjectId(c.id))}}},{$group:{_id:'$category_id',data:{$push:'$$ROOT'}}}])` – chridam Feb 28 '22 at 17:24
  • @chridam Thank you very much! Your code is working very effectively! – lai9fox Feb 28 '22 at 17:45

0 Answers0