Mongodb 在聚合结果中重命名数组子文档
我正在使用mongodb 3.4。运行我的聚合后,我的结果如下所示。我在两个系列之间进行了连接Mongodb 在聚合结果中重命名数组子文档,mongodb,aggregation-framework,Mongodb,Aggregation Framework,我正在使用mongodb 3.4。运行我的聚合后,我的结果如下所示。我在两个系列之间进行了连接 [ { "_id": { // rename _id to main "id": "ID_001", "name": "Fred flinstone Inc" }, "types": [ { "typeId": "TYPE1", "locations": [ {
[ {
"_id": { // rename _id to main
"id": "ID_001",
"name": "Fred flinstone Inc"
},
"types": [
{
"typeId": "TYPE1",
"locations": [
{
"locationName": "Sydney", // rename locationName to name
"units": [
{
"unitId": "PHG_BTG1" // remove the unitId, i just want the value
}
]
},
{
"locationName": "Brisbane",
"units": [
{
"unitId": "PHG_KTN1"
},
{
"unitId": "PHG_KTN2"
}
]
}
]
}
] } ]
我想把它投影为
[
{
"main": {
"id": "ID_001",
"name": "Fred flinstone Inc"
},
"types": [
{
"typeId": "TYPE1",
"locations": [
{
"name": "Sydney",
"units": [
"PHG_BTG1"
]
},
{
"name": "Brisbane",
"units": [
"PHG_KTN1",
"PHG_KTN2"
]
}
]
}
]
}
]
我该怎么做?我尝试了$project的各种组合,但失败了。
范例
将正确重命名locations.name,但该值显示[Sydney,Brisbane]的数组。当我尝试类似locations.units的东西时也是如此
我试图再次放松,但它会显示一个空的结果。任何帮助都是非常感谢的。只有在您试图使用它的形式中才真正做到“包含”或“独占”。因此,虽然您可以执行“types”:{“typeId”:1}
以仅返回数组中的那些项,但实际上不能仅通过“包含”或“排除”来更改底层结构
正如您所发现的,类似于:
{ "$project": {
"types.locations.units": "$types.locations.units.unitId"
}}
与您期望的不同,因为MongoDB将每个值和作为“映射”数组元素查看:
"types" : [
{
"locations" : [
{
"units" : [
[
[
"PHG_BTG1"
],
[
"PHG_KTN1",
"PHG_KTN2"
]
]
]
}
或者更糟:
{ "$project": {
"types.typeId": "$types.typeId"
}}
作为:
所以这里并不真正需要“数组的数组”。这就让我们明白了为什么这实际上是“速记”,用于使用您真正想要使用的运算符
要“转换”数组,请使用:
返回所需的格式:
{
"main" : {
"id" : "ID_001",
"name" : "Fred flinstone Inc"
},
"types" : [
{
"typeId" : "TYPE1",
"locations" : [
{
"name" : "Sydney",
"units" : [
"PHG_BTG1"
]
},
{
"name" : "Brisbane",
"units" : [
"PHG_KTN1",
"PHG_KTN2"
]
}
]
}
]
}
本质上,每个“数组”都被“重新映射”为只返回您实际指定的内部表示的结构。这就是为什么要嵌套在其他表达式中,以处理每个数组元素的内部数组
还请注意,由于我们基本上是在“重新编写”“type”
属性,因此中同名属性的默认行为通常是“复制”并保留顺序,即“type”
实际上是现有文档结构的一部分,而“main”
不是。因此,“类型”
将由标准投影包含表示为“第一”
“重新写入”意味着这被视为一个新元素,因此键的顺序现在与投影中的相同,即“main”
“type”,而不是相反
"types" : [
{
"typeId" : [
"TYPE1"
]
}
]
{ "$project": {
"_id": 0,
"main": "$_id",
"types": {
"$map": {
"input": "$types",
"as": "t",
"in": {
"typeId": "$$t.typeId",
"locations": {
"$map": {
"input": "$$t.locations",
"as": "l",
"in": {
"name": "$$l.locationName",
"units": {
"$map": {
"input": "$$l.units",
"as": "u",
"in": "$$u.unitId"
}
}
}
}
}
}
}
}
}}
{
"main" : {
"id" : "ID_001",
"name" : "Fred flinstone Inc"
},
"types" : [
{
"typeId" : "TYPE1",
"locations" : [
{
"name" : "Sydney",
"units" : [
"PHG_BTG1"
]
},
{
"name" : "Brisbane",
"units" : [
"PHG_KTN1",
"PHG_KTN2"
]
}
]
}
]
}