Reputation: 43
Is there a way in mongoDb to merge documents based on id. For eg:
/*1*/{
"id" : "xxxxxx",
"pages" : {
"name" : "Page50-50",
"pageid" : "Page50-50",
"icon" : "/images/cmstemplates/2column.png",
"children" : []
},
"permissions" : [
{
"grpName" : "Admin",
"grants" : [
"View",
"Delete",
"Edit"
]
},
{
"grpName" : "Users",
"grants" : [
"View"
]
}
]
}
/*2*/
{
"id" : "xxxxxx",
"pages" : {
"name" : "AboutUs",
"pageid" : "AboutUs",
"icon" : "/images/cmstemplates/1column.png",
"children" : []
},
"permissions" : [
{
"grpName" : "Student",
"grants" : [
"View",
"Delete"
]
}
]
}
Expected Output:
{
"id" : "xxxxxx",
"pages" : [{
"name" : "Page50-50",
"pageid" : "Page50-50",
"icon" : "/images/2column.png",
"children" : [],
"permissions" : [
{
"grpName" : "Admin",
"grants" : [
"View",
"Delete",
"Edit"
]
},
{
"grpName" : "Users",
"grants" : [
"View"
]
}
]
},{
"name" : "AboutUs",
"pageid" : "AboutUs",
"icon" : "/images/1column.png",
"children" : [],
"permissions" : [
{
"grpName" : "Student",
"grants" : [
"View",
"Delete"
]
}
]
}]
}
The permissions params in the expected output should come inside pages, and pages should group into an array. I used $group and was able to group the pages, but i am not able to figure out how can i add permissions param inside pages. I am using mongodb 3.2.
Thanks.
Upvotes: 1
Views: 1874
Reputation: 10111
Use $group
db.getCollection('Collection').aggregate([{
$group: {
"_id": "$_id",
"pages": {
$push: "$pages"
}
}
}])
Upvotes: 2