我正在尝试编写一个查询,它将给出多级分组的结果。
如下所示:
firstLevel: [
{
SecondLevel-1:
[
{//Some Data},
{//Some Data}
]
},
{
SecondLevel-2:
[
{//Some Data},
{//Some Data}
]
}
]下面是我的MongoPlayGround地址
https://mongoplayground.net/p/b7VzoXavw9r
我能够得到第一级分组,尽管我想要以下格式的结果。
[
{
"section-1": [
{
"terminal-1":[
{
"_id": ObjectId("5e93fea52f804ab99b12e7c0"),
"isActive": true,
"isDelete": false
},
{
"_id": ObjectId("5e93fea52f804ab99b12e7c1"),
"isActive": true,
"isDelete": false
}
]
},
"terminal-2":[
{
"_id": ObjectId("5e93fea52f804ab99b12e7c2"),
"isActive": true,
"isDelete": true
}
]
]
}
]发布于 2020-12-09 16:58:20
$group由section和terminal生成唯一的对象数组,并将终端$group的键值对转换为section和terminal数组,在转换为section 后替换根中的object
db.settings.aggregate([
{
$group: {
_id: {
section: "$section",
terminal: "$terminal"
},
v: {
$addToSet: {
_id: "$_id",
isActive: "$isActive",
isDelete: "$isDelete"
}
}
}
},
{
$group: {
_id: "$_id.section",
v: {
$push: { k: "$_id.terminal", v: "$v" }
}
}
},
{
$replaceRoot: {
newRoot: {
$arrayToObject: [[
{
k: "$_id",
v: { $arrayToObject: "$v" }
}
]]
}
}
}
])https://stackoverflow.com/questions/65211577
复制相似问题