[英]Using $unwind with nested subdocuments
I have a collection with the following structure: 我有一个具有以下结构的集合:
{
{
node: 'ST20'
Ds:{
699:{
TotCM: 300
Docsis20: 200
Docsis30: 100
}
705:{
TotCM: 250
Docsis20: 150
Docsis30: 100
}
}
}
{
node: 'ST21'
Ds:{
651:{
TotCM: 200
Docsis20: 100
Docsis30: 100
}
699:{
TotCM: 100
Docsis20: 0
Docsis30: 100
}
}
}
}
As you can see, I have a document that represents a node. 如您所见,我有一个代表节点的文档。 Each node, has different channels. 每个节点具有不同的通道。 My objective is see how many cablemodems I have in each channel. 我的目标是查看每个通道中有多少个电缆调制解调器。 From upfront, I don't know the channels that I have in each node. 从头开始,我不知道我在每个节点中拥有的渠道。 So I would like to have something like this: 所以我想要这样的东西:
{ node: 'ST20', Ds: 699, TotCM: 300, Docsis20: 200, Docsis30:100 }
{ node: 'ST20', Ds: 705, TotCM: 250, Docsis20: 150, Docsis30:100 }
{ node: 'ST21', Ds: 651, TotCM: 200, Docsis20: 100, Docsis30:100 }
{ node: 'ST21', Ds: 699, TotCM: 100, Docsis20: 0, Docsis30:100 }
I tried the following query: 我尝试了以下查询:
db.statsNodos.aggregate(
{ $project: {_id:0,Ds:1,node:1}},
{ $unwind: "$Ds"}
).pretty()
But I get the original document. 但是我得到了原始文件。 And, as you can see, they are nested documents and not an array of documents. 而且,如您所见,它们是嵌套文档,而不是文档数组。 Maybe I don't have to use $unwind
and there is another way to get this. 也许我不必使用$unwind
,还有另一种方式来实现这一点。 Can you tell me? 你能告诉我吗?
Given your example document structure : 给定您的示例文档结构:
{ node: 'ST21',
Ds: {
"651":{ TotCM: 200, Docsis20: 100, Docsis30: 100 },
"699":{ TotCM: 100, Docsis20: 0, Docsis30: 100 }
}
}
You can utilise operator $objectToArray to pivot your field channels
name into value. 您可以利用运算符$ objectToArray将字段channels
名称转换为值。 For example: 例如:
{"$project": {
"_id": 0,
"node": 1,
"tmp": { "$objectToArray": "$Ds" }
}
},
{"$unwind": "$tmp" },
{"$project": {
"node": 1,
"Ds": "$tmp.k",
"TotCM": "$tmp.v.TotCM",
"Docsis20": "$tmp.v.Docsis20",
"Docsis30": "$tmp.v.Docsis30"
}
}
I would also recommend to reconsider your MongoDB Data Schema for easier querying. 我还建议重新考虑您的MongoDB数据架构,以简化查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.