我有一个具有以下结构的mongodb数据库
{
"_id" : ObjectId("56f1492e95136b7d113dd1c7"),
"name" : "Terminal 1 Sample Port",
"owl" : [
{
"macId" : "443A3",
"hostName" : "Old",
"group" : "High Mast Lighting",
"subGroup" : "Public Marshalling Area"
},
{
"macId" : "4437",
"hostName" : "LED Mast 7",
"group" : "High Mast Lighting",
"subGroup" : "Public Marshalling Area"
},
{
"macId" : "4437190",
"hostName" : "Ground Floor",
"group" : "Terminal 1",
"subGroup" : "Ground Floor"
},
{
"macId" : "44387",
"hostName" : "LED 80mt ",
"group" : "High Mast Lighting",
"subGroup" : "Commercial Goods Area"
},
]
}
我想转换为以下结构
[
{ "name": "High Mast Lighting",
"subvalues": [{
"name": "Public Marshalling Area",
"subvalues":
[{ "id": "44373",
"name": "Old 3"
},
{ "id": "443778",
"name": "LED Light Mast 7"
}]
}]
}
]
我能够使用lodash做同样的事情,但我想知道使用mongodb聚合框架是否可以实现相同
答案 0 :(得分:0)
你需要玩它 - 但作为输出你会得到你想要的东西:
db.a.aggregate([
{$unwind:"$owl"},
{$group: {
_id:{"name":"$owl.group", "subvaluesName":"$owl.subGroup" },
subvalues1: { $addToSet:{ "id": "$owl.macId" , "name":"$owl.hostName"}}
}},
{
$project:{
_id:0,
name:"$_id.name",
subvalues:{
name:"$_id.subvaluesName",
subvalues:"$subvalues1"
}
}}
])
输出:
{
"name" : "High Mast Lighting",
"subvalues" : {
"name" : "Public Marshalling Area",
"subvalues" : [
{
"id" : "443A3",
"name" : "Old"
},
{
"id" : "4437",
"name" : "LED Mast 7"
}
]
}
}
并保持更改使用$ out作为最后一个聚合阶段。