Reputation: 11637
I am using mongodb
I have n houses, each house has streetid, houseid, neighborhoodid
{streetid,houseid,neighborhood}
{av,1,A},{av,2,A},{av,3,A}
{av,5,B},{av,6,B},{av,7,B}
{rd,1,A},{rd,22,A},{rd,33,A}
I want to group by street so that each street will have an array of neighborhoods (a street can span several neighborhoods ) and each neighborhood will have a list of houses that are in it(the houses must also belong to the street)
the result should be something like
{av,[{A ,[1,2,3]}, {B,[5,6,7]}]}
// street A spans neighborhood A and B each with its houses
{rd,[{A ,[1,22,33]}]}
// street rd spans neighborhood A with its houses
Upvotes: 0
Views: 356
Reputation: 1035
This should work:
db.example.aggregate( [
{
$group: {
_id: { neighbourhood: "$neighbourhood", streetId: "$streetId" },
house: { $addToSet: "$houseId" }
}
},
{
$group: {
_id: { street: "$_id.streetId" },
housesInNeighbourHood: { $addToSet: { neighbourhoodId: "$_id.neighbourhood", houseId:"$house" } }
}
}
])
Upvotes: 1