I have to filter data based on a criteria and set a field isObtained
true or false. Then I am trying to group the data based on field grade
. This is my data:
{
"school": "xyz",
"studentName": "John Doe",
"grade": "first",
"Hobbies": [
"Painting",
"Singing"
],
"language": [
"English"
],
"sport": "Badminton",
"totalStudyHours": 85
},
{
"school": xyz,
"studentName": "Jane Doe",
"grade": "third",
"Hobbies": [
"Painting",
],
"language": [
"Spanish"
],
"sport": "Karate",
"totalStudyHours": 65
},
{
"school": "xyz",
"studentName": "joey",
"grade": "first",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Cricket",
"totalStudyHours": 75,
"ispassed": true,
},
{
"studentName": "jason",
"grade": "third",
"Hobbies": [
"Painting",
],
"language": [
"English",
"Spanish"
],
"sport": "Tennis",
"totalStudyHours": 95,
"isObtained": true
},
{
"studentName": "mike",
"grade": "third",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Badminton",
"totalStudyHours": 70,
"isObtained": true
}
The expected output is
[
{
"grade": "first",
"values": [
{
"studentName": "John Doe",
"grade": "first",
"Hobbies": [
"Painting",
"Singing"
],
"language": [
"English"
],
"sport": "Badminton",
"totalStudyHours": 85,
"isObtained": true
},
{
"studentName": "joey",
"grade": "first",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Cricket",
"totalStudyHours": 75,
"isObtained": true
}
]
},
{
"grade": "third",
"values": [
{
"studentName": "jason",
"grade": "third",
"Hobbies": [
"Painting",
],
"language": [
"English",
"Spanish"
],
"sport": "Tennis",
"totalStudyHours": 95,
"isObtained": true
},
{
"studentName": "mike",
"grade": "third",
"Hobbies": [
"Singing"
],
"language": [
"English",
"Italian"
],
"sport": "Badminton",
"totalStudyHours": 70,
"isObtained": true
}
]
}
]
In the mongoDb query, the isObtained
field is set based on what field we want. For example, if we want records with sport as "Badminton" then the isObtained
field will be true when sport is Badminton and false otherwise.
Here is the query, but I am facing problem in grouping based on grade
.
db.students.aggregate([
{
"$match": {
"$and": [
{
"school": "xyz"
}
]
}
},
{
"$project": {
"sport": 1,
"language": 1,
"hobbies": 1,
"isObtained": {
"$and": [
{
"$eq": [
"$sport",
"Badminton"
]
}
]
}
}
}
question from:
https://stackoverflow.com/questions/65914720/how-to-group-data-using-mongo-template