在一个集合中,考虑到我们具有matchQuery {oid:somex}的以下文档:
[{
_id: id1,
parentid:ParentId1,
somefields:<some values>
},
{
_id: id2,
parentid:ParentId1,
somefields:<some values>
},
{
_id: id3,
parentid:ParentId2,
somefields:<some values>
},
{
_id: id4,
parentid:ParentId3,
somefields:<some values>
},
{
_id: id5,
parentid:id1,
somefields:<some values>
},
{
_id: id6,
parentid: id1,
somefields:<some values>
},
{
_id: id7,
parentid: id2,
somefields:<some values>
},
{
_id: id8,
parentid: id3,
somefields:<some values>
},
{
_id: id9,
parentid: id3,
somefields:<some values>
},
{
_id: id10,
parentid: id4,
somefields:<some values>
},
{
_id: id11,
parentid: id5,
somefields:<some values>
},
{
_id: id12,
parentid: id5,
somefields:<some values>
},
{
_id: id13,
parentid: id5,
somefields:<some values>
},
{
_id: id14,
parentid: id13,
somefields:<some values>
},
{
_id: id15,
parentid: id13,
somefields:<some values>
},
]
仅使用以下汇总查询,我就能在一个级别上实现这一目标:
db.random.aggregate([ { $match:{oid:"somex"}},{$group:{ _id:'$parentid', result: { $push: "$$ROOT" } } }]).toArray()
因此,它基于父代以平面分组形式输出。也仅将结果与parentId及其直接子文档分组。我也想获取父文档字段,理想情况下也要获取父文档的所有字段。
所以我想将其分组并按原样嵌套:
[{
_id: id1,
parentid:ParentId1,
somefields:<some values>,
children: [{
_id: id5,
parentid:id1,
somefields:<some values>,
children:[{
_id: id11,
parentid: id5,
somefields:<some values>
},
{
_id: id12,
parentid: id5,
somefields:<some values>
},
{
_id: id13,
parentid: id5,
somefields:<some values>,
children: [{
_id: id14,
parentid: id13,
somefields:<some values>
},
{
_id: id15,
parentid: id13,
somefields:<some values>
}]
}]
},
{
_id: id6,
parentid: id1,
somefields:<some values>
}]
},
{
_id: id2,
parentid:ParentId1,
somefields:<some values>,
children: [{
_id: id7,
parentid: id2,
somefields:<some values>
}]
},
{
_id: id3,
parentid:ParentId2,
somefields:<some values>,
children: [{
_id: id8,
parentid: id3,
somefields:<some values>
},
{
_id: id9,
parentid: id3,
somefields:<some values>
}]
},
{
_id: id4,
parentid:ParentId3,
somefields:<some values>,
children:[{
_id: id10,
parentid: id4,
somefields:<some values>
}]
}
]
有人可以建议我通过聚合查询来达到预期结果吗?