I am trying to aggregate and reform the mongodb data and sort them based on the name. All the data belongs to same collection.
Node js, express js, mongodb
{
"_id" : "1"
"c_cat" : "one",
"c_level" : "levelone",
"c_group" : "groupone"
}
{
"_id" : "2"
"c_cat" : "one",
"c_level" : "levelone",
"c_group" : "grouptwo",
}
{
"_id" : "3"
"c_cat" : "one",
"c_level" : "leveltwo",
"c_group" : "groupthree",
}
{
"_id" : "4"
"c_cat" : "two",
"c_level" : "leveltwo",
"c_group" : "groupfour",
}
{
"_id" : "5"
"c_cat" : "two",
"c_level" : "leveltwo",
"c_group" : "groupfive",
}
{
"_id" : "6"
"c_cat" : "two",
"c_level" : "levelfive",
"c_group" : "groupfive",
}
The expected actual result after reshaping with nested structure should be as follows
{
"c_cat" : "one"
{
"c_level" : "levelone"
{
"c_group" : ["groupone", "grouptwo"]
}
"c_level" : "leveltwo"
{
"c_group" : ["groupthree"]
}
}
}
{
"c_cat" : "two"
{
"c_level" : "leveltwo"
{
"c_group" : ["groupfour", "groupfive"]
}
"c_level" : "levelfive"
{
"c_group" : ["groupfive"]
}
}
}
using the recommended script i get the excepted result
db.collection.aggregate([
{
"$group": {
"_id": {
"c_cat": "$c_cat",
"c_level": "$c_level"
},
c_group: {
$push: "$c_group"
},
"bookCount": {
"$sum": 1
}
}
},
{
"$group": {
"_id": "$_id.c_cat",
"c_level": {
"$push": {
"c_level": "$_id.c_level",
"c_group": "$c_group"
},
},
"count": {
"$sum": "$bookCount"
}
}
}
])
I used the same to pass and render the output to another page using below
router.get('/catalogue', function(req, res) {
var course = {};
Ct_course.aggregate([
{
"$group": {
"_id": {
"c_cat": "$c_cat",
"c_level": "$c_level"
},
c_group: {
$push: "$c_group"
},
"bookCount": {
"$sum": 1
}
}
},
{
"$group": {
"_id": "$_id.c_cat",
"c_level": {
"$push": {
"c_level": "$_id.c_level",
"c_group": "$c_group"
},
},
"count": {
"$sum": "$bookCount"
}
}
}
],
function(err, results){ course = results;
console.log(course);
res.render("course/catalogue",{course:course});
});
});
The result i am getting in console is
[ { _id: 'Safety',
c_level: [ [Object], [Object], [Object], [Object] ],
count: 13 },
{ _id: 'D Level',
c_level: [ [Object], [Object], [Object], [Object], [Object] ],
count: 18 },
{ _id: 'C Level',
c_level: [ [Object], [Object], [Object], [Object] ],
count: 45 },
{ _id: 'A Level', c_level: [ [Object] ], count: 1 },
{ _id: 'B Level', c_level: [ [Object], [Object] ], count: 18 },
{ _id: 'Special Courses',
c_level:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
count: 34 } ]
The aggregate works fine in mongoshell, here it need to array array values to handlebar page