Home > database >  How can I use Aggregate for models?
How can I use Aggregate for models?

Time:04-09

I have a model with name Course like below that there is a section model inside it(embed):

{
    "_id": "624e8e6a870036ee6376d675",
    "standardCode": "21321 JH 123",
    "name": "JS programming bootcamp",
    "description": "",
    "start_date": "4/9/2022",
    "picture": "course-135526.jpg",
    "sections": [
                "624e8eb9870036ee6376d690",
                "624eda279290d7d518de58a9",
                "624ee9a51fbdb9c1986134dd"
    ]
    "createAt": "Thu - 4/8/2022"
},
{
    "_id": "624e8e6a870036fd3276d213",
    "standardCode": "232 ab 333",
    "name": "React programming bootcamp",
    "description": "",
    "start_date": "4/9/2022",
    "picture": "course-135526.jpg",
    "sections": []
    "createAt": "Thu - 4/8/2022"
}

And the Section model is like:

{
    "_id": "624e8eb9870036ee6376d690",
    "name": "intro",
    "description": "",
    "price": 0,
    "type": "classroom",        
},
{
    "_id": "624eda279290d7d518de58a9",
    "name": "about js",
    "description": "",
    "price": 25000,
    "type": "classroom",        
},
{
    "_id": "624ee9a51fbdb9c1986134dd",
    "name": "define variable",
    "description": "",
    "price": 30000,
    "type": "classroom",        
}

That's it my two model that course and sections is very bigger that I write here but this info is Ok for all of them. And so, I want this from output:

{
    "_id": "624e8e6a870036fd3276d213",
    "sumPrice": 0,
    "numSection": 0,
    "standardCode": "232 ab 333",
    "name": "React programming bootcamp",
    "description": "",
    "start_date": "4/9/2022",
    "picture": "course-135526.jpg",
    "createAt": "Thu - 4/8/2022"
},
{
    "_id": "624e8e6a870036ee6376d675",
    "sumPrice": 55000,
    "numSection": 3,
    "standardCode": "21321 JH 123",
    "name": "JS programming bootcamp",
    "description": "",
    "start_date": "4/9/2022",
    "picture": "course-135526.jpg",
    "createAt": "Thu - 4/8/2022"
}

Which SumPrice is sum of sections prices and numSection is sum of sections number.

CodePudding user response:

db.Course.aggregate([
  {
    $lookup: {
      from: "Section",
      localField: "sections",
      foreignField: "_id",
      as: "sections"
    }
  },
  {
    $set: {
      sumPrice: {
        $sum: "$sections.price"
      },
      numSection: {
        $size: "$sections"
      }
    }
  },
  {
    $unset: "sections"
  }
])

mongoplayground

  • Related