mongo聚合操作符$unwind

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/

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值