Home > Blockchain >  Grouping unique number Monngodb
Grouping unique number Monngodb

Time:05-10

I have these example data from lookup and unwind

{
  id: 1a1,
  package:2ab,
  question:{
  no_soal:1,
  score:10
  },
  id: 1a1,
  package:2ab,
  question:{
  no_soal:1,
  score:20
  },
  id: 1a1,
  package:2ab,
  question:{
  no_soal:2,
  score:20
  },
  id: 1a1,
  package:2ab,
  question:{
  no_soal:3,
  score:5
  },
  id: 1a1,
  package:2ab,
  question:{
  no_soal:4,
  score:10
  },
  id: 1a1,
  package:2ab,
  question:{
  no_soal:4,
  score:20
  },
  id: 1b2,
  package:1ab,
  question:{
  no_soal:1,
  score:10
  },
  id: 1b2,
  package:1ab,
  question:{
  no_soal:2,
  score:10
  },
}

well i have to group it by the id and package and make the question as an array object like this one bellow. The no_soal must contain unique number taken from the first data. this is the EXPECTED OUTPUT

{
  id:1a1,
  package:2ab,
  question:[
    {no_soal:1,score:10},{no_soal:2,score:20},{no_soal:3,score:5},{no_soal:4,score:10}
  ]
},
{
  id:1b2,
  package:1ab,
  question:[
    {no_soal:1,score:10},{no_soal:2,score:10}
  ]
}

right now i alrady able to regroup it with this code:

{
 $group:{
  "id": "$id",
  "package": {
    "$first": "$package"
  },
  "question": {
    "$push": "$question"
  }
 }
}

but still not as same as the expected output. the question field still not contain unique number, kinda confuse how to make it so. Can you guys tell me what should i add in this code? thank you for trying to answer this question

this is the FALSE OUTPUT that i get from the code i wrote

 {
  id:1a1,
  package:2ab,
  question:[
    {no_soal:1,score:10}{no_soal:1,score:20},{no_soal:2,score:20},{no_soal:3,score:5}, 
    {no_soal:4,score:10},{no_soal:4,score:20}
  ]
},
{
  id:1b2,
  package:1ab,
  question:[
    {no_soal:1,score:10},{no_soal:2,score:10}
  ]
}

CodePudding user response:

Just group by both id and no_soal first to remove any equivalents then group by id normally. Your example data and query contains some formatting errors, but nevertheless:

db.collection.aggregate([
  {
    $group: {
      "_id": {
        "id": "$id",
        "no_soal": "$question.no_soal"
      },
      "package": {
        "$first": "$package"
      },
      "question": {
        "$first": "$question"
      }
    }
  },
  {
    $group: {
      "_id": "$_id.id",
      "package": {
        "$first": "$package"
      },
      "question": {
        "$addToSet": "$question"
      }
    }
  }
])

mongoplayground

  • Related