After 3 collections was joined and many many groupings later i have documents like:
{
"Request" : "first",
"TotalRequests" : 12,
"Organization" : "A",
"TotalRequestsByOrganization" : 3,
"user" : "John Smith",
"TotalRequestsByUserInOrganization" : 1
},
{
"Request" : "first",
"TotalRequests" : 12,
"Organization" : "A",
"TotalRequestsByOrganization" : 3,
"user" : "John Galt",
"TotalRequestsByUserInOrganization" : 2
},
{
"Request" : "first",
"TotalRequests" : 12,
"Organization" : "B",
"TotalRequestsByOrganization" : 7,
"user" : "Chris Evans",
"TotalRequestsByUserInOrganization" : 4
},
{
"Request" : "first",
"TotalRequests" : 12,
"Organization" : "B",
"TotalRequestsByOrganization" : 7,
"user" : "Charlie",
"TotalRequestsByUserInOrganization" : 3
},
{
"Request" : "second",
"TotalRequests" : 3,
"Organization" : "B",
"TotalRequestsByOrganization" : 3,
"user" : "James Anthony",
"TotalRequestsByUserInOrganization" : 3
}
etc.
How to group my documents, when "user" and "TotalRequestsByUserInOrganization" is nested into "Organization" and "TotalRequestsByOrganization", and they are part of "Request" and "TotalRequests"?
What i want in result:
{
"Request" : {
"name" : "first",
"TotalRequests" : 12,
"Organization": {
"Orgname": "A",
"TotalRequestsByOrganization": 3,
"users": {
"user" : "John Smith",
"TotalRequestsByUserInOrganization" : 1,
"user" : "John Galt",
"TotalRequestsByUserInOrganization" : 2
}}}}
CodePudding user response:
You can achieve the expected result by 2 $group:
$groupby finest level:Request, TotalRequests, Organization, TotalRequestsByOrganization; use$pushto put alluserandTotalRequestsByUserInOrganizationtuple into an arrayuser$groupby coarser level:Request, TotalRequests; use$pushto put allOrgname,TotalRequestsByOrganizationandusersarray into an arrayOrganization- At the most coarse level,
$projectthe field to wrangle the output to your expected format
Here is the Mongo playground for your reference.
