[英]MongoDB Aggregate Facet & Group
我有以下数据集,我希望在报告中对其进行总结。 基本上我正在寻找状态计数(按状态)和每个键的组。 我已经尝试了几种方法来完成这个无济于事。
[
{
"_id": ObjectId("635f808302d5f6cb7c293298"),
"key": "scientific",
"custom_properties": [
{
"namespace": "common metadata",
"key": "status",
"scope": "public",
"value": "To be uploaded",
"inherited": null
},
{
"namespace": "common metadata",
"key": "version",
"scope": "public",
"value": "1.0",
"inherited": null
},
{
"namespace": "common metadata",
"key": "start date",
"scope": "public",
"value": "1642550400000",
"inherited": null
},
]
},
{
"_id": ObjectId("635f809d02d5f6cb7c29353c"),
"key": "contracts",
"custom_properties": [
{
"namespace": "common metadata",
"key": "status",
"scope": "public",
"value": "To be reviewed",
"inherited": null
},
{
"namespace": "common metadata",
"key": "version",
"scope": "public",
"value": "",
"inherited": null
},
{
"namespace": "contracts",
"key": "expiry date",
"scope": "public",
"value": "",
"inherited": null
},
{
"namespace": "common metadata",
"key": "start date",
"scope": "public",
"value": "",
"inherited": null
},
]
},
{
"_id": ObjectId("635f80a002d5f6cb7c293588"),
"key": "contracts",
"custom_properties": [
{
"namespace": "common metadata",
"key": "status",
"scope": "public",
"value": "To be uploaded",
"inherited": null
},
{
"namespace": "common metadata",
"key": "version",
"scope": "public",
"value": "",
"inherited": null
},
]
}
]
我正在寻找 Group 和 Facet,我不确定先完成哪个。
所需的 output 应汇总状态计数和按键分组,并且应类似于以下内容......
[
{
scientific: [{
'To be reviewed': 0,
'To be uploaded': 1
}],
contracts: [{
'To be reviewed': 1,
'To be uploaded': 1
}],
}
]
注意:键和状态值都是动态的。 也就是说,我们可以引入一个新的状态,并且随着时间的推移将引入几个密钥。
您可以使用以下管道执行此操作:
所有这一切都需要几个$group
阶段来计算,然后进行一些结构操作以获得所需的 output
db.collection.aggregate([
{
$group: {
_id: {
key: "$key",
statusVal: {
"$getField": {
"field": "value",
"input": {
"$arrayElemAt": [
{
$filter: {
input: "$custom_properties",
cond: {
$eq: [
"$$this.key",
"status"
]
}
}
},
0
]
},
}
}
},
sum: {
$sum: 1
}
}
},
{
$group: {
_id: "$_id.key",
types: {
$push: {
k: "$_id.statusVal",
v: "$sum"
}
}
}
},
{
$group: {
_id: null,
root: {
$push: {
k: "$_id",
v: {
"$arrayToObject": "$types"
}
}
}
}
},
{
$replaceRoot: {
newRoot: {
"$arrayToObject": "$root"
}
}
}
])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.