具有嵌套数组的mongodb聚合查询

时间:2016-07-10 18:37:16

标签: mongodb mongodb-query aggregation-framework

我正在使用mongodb

我有n个房子,每个房子都有streetid,houseid,neighborhoodid

{streetid,houseid,邻里}

{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}

我想按街道分组,以便每条街道都有一系列社区(街道可以跨越几个街区),每个街区都会有一个房屋清单(房屋也必须属于街道)

结果应该是

{av,[{A,[1,2,3]},{B,[5,6,7]}}}

// street A跨越A和B附近的房屋

{rd,[{A,[1,22,33]}]}

// street rd跨越邻居A及其房屋

1 个答案:

答案 0 :(得分:1)

这应该有效:

db.example.aggregate( [
  { 
    $group: { 
      _id:   { neighbourhood: "$neighbourhood", streetId: "$streetId" }, 
      house: { $addToSet: "$houseId" } 
    } 
  }, 
  { 
    $group: {
      _id: { street: "$_id.streetId" }, 
      housesInNeighbourHood: { $addToSet: { neighbourhoodId: "$_id.neighbourhood", houseId:"$house" } } 
    } 
  } 
])