我的mongoDB集合中有上千个文档,其中每个文档都表示这样一首歌的数据:
{
"_id": ObjectID("612e03a790c3d3189845589b"),
"artist": "3 Doors Down",
"title": "Landning in London",
"album": "Another 700 Miles",
"genre": "Seventeen Days",
"trackNumber": 5,
"year": 2005,
"rating": 3,
"duration": "4:32",
"country": "United States",
}现在,在聚合管道的帮助下,我想通过以下方式对集合进行分组。到目前为止,我可以进行一个阶段的分组,但是我很难通过完整的根文档直到结束,并完成这个嵌套分组。
列出所有类型
{
[
{
"genreName": "Alternative Rock",
"artists": [
{
"artistName": "3 Doors Down",
"albums": [
{
"albumName": "Seventeen Days",
"songs": [
{
"_id": ObjectID(612e03a790c3d3189845589b),
"artist": "3 Doors Down",
"title": "Landning in London",
"album": "Another 700 Miles",
"genre": "Seventeen Days",
"trackNumber": 5,
"year": 2005,
"rating": 3,
"duration": "4:32",
"country": "United States",
}
]
}
]
}
]
}
]
}发布于 2022-02-03 10:23:18
这一项应能发挥作用:
db.collection.aggregate([
{
$group: {
_id: { genreName: "$genre", artistName: "$artist", albumName: "$album" },
songs: { $push: "$$ROOT" }
}
},
{
$group: {
_id: { genreName: "$_id.genreName", artistName: "$_id.artistName" },
albums: { $push: { albumName: "$_id.albumName", songs: "$songs" } }
}
},
{
$group: {
_id: "$_id.genreName",
artists: { $push: { artistsName: "$_id.artistsName", albums: "$albums" } }
}
},
{ $project: { _id: 0, genreName: "$_id", artists: 1 } }
])https://stackoverflow.com/questions/70968863
复制相似问题