0

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

1
  • Your documents are not valid. Commented Jul 10, 2016 at 19:54

1 Answer 1

1

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" } } 
    } 
  } 
])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.