1.原始数据
2.需求
1.按条件获取所有停机原因及对应的停机时长数据
2.按条件获取指定停机类型下的停机原因及停机时长
3.操作
3.1 获取所有停机原因及时长
db.stop_reason_duration_daily_data.aggregate([
{'$match': {"timestamp": {"$gte": ISODate("2020-10-01T00:00:00.000+0000"), "$lt": ISODate("2020-12-24T00:00:00.000+0000")},
}
},
{'$unwind': '$reason_detail_res'},
{'$group': {
'_id': '$reason_detail_res.name',
'count': {'$sum': '$reason_detail_res.value'},
}
},
{'$project': {'_id': 0,
'name': '$_id',
'value': '$count'
}
}
])
3.2 指定停机分类或停机类型下的停机原因及时长
db.stop_reason_duration_daily_data.aggregate([
{'$match': {"timestamp": {"$gte": ISODate("2020-10-01T00:00:00.000+0000"), "$lt": ISODate("2020-12-24T00:00:00.000+0000")},
}
},
{'$unwind': '$reason_detail_res'},
{'$match': {'reason_detail_res.reason_class': '速度损失', 'reason_detail_res.shut_down_type': '计划外停机'}}, # 此处用来过滤指定停机分类或停机类型
{'$group': {
'_id': '$reason_detail_res.name',
'count': {'$sum': '$reason_detail_res.value'},
}
},
{'$project': {'_id': 0,
'name': '$_id',
'value': '$count'
}
}
])
4.$unwind 拆解数组字段
4.1 定义
- 定义 field版
{ $unwind: <field path> }
- 定义document版
{
$unwind:
{
path: <field path>,
includeArrayIndex: <string>,
preserveNullAndEmptyArrays: <boolean>
}
}
path
你要打散的字段
includeArrayIndex
,可选的。一个新字段的名称,用于保存元素的数组索引。名称不能以美元符号开头。
preserveNullAndEmptyArrays
,可选的。如果为true,则如果path为null,缺失或空数组,则$unwind
输出文档。如果为false,如果path为null,缺少或为空数组,$unwind则不会输出文档。默认值为false。
4.2 示例:
- 原始数据
db.inventory.insertOne({ "_id" : 1, "item" : "ABC1", sizes: [ "S", "M", "L"] })
- 拆分数组
db.inventory.aggregate( [ { $unwind : "$sizes" } ] )
- 拆分结果
{ "_id" : 1, "item" : "ABC1", "sizes" : "S" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "M" }
{ "_id" : 1, "item" : "ABC1", "sizes" : "L" }
参考:https://docs.mongodb.com/manual/reference/operator/aggregation/unwind/