MongoDb 分组统计查询


db.getCollection("CommonStatisticsLog").aggregate([
    {
        "$match": {
            "CreateTime": {
                "$gte": ISODate("2025-02-13T09:00:00Z"),
                "$lte": ISODate("2025-02-13T09:59:59Z")
            },
            "NeedStatisticsHourLog": true
        }
    },
    {
        "$group": {
            "_id": {
                "ProductKey": "$ProductKey",
                "DeviceName": "$DeviceName",
                "LogType": "$LogType",
                "StatisticsType": "$StatisticsType"
            },
            "TotalTimes": { "$sum": "$Times" },
            "TotalSeconds": { "$sum": "$Seconds" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "ProductKey": "$_id.ProductKey",
            "DeviceName": "$_id.DeviceName",
            "LogType": "$_id.LogType",
            "StatisticsType": "$_id.StatisticsType",
            "DateCode": 2025021309,
            "TotalTimes": "$TotalTimes",
            "TotalSeconds": "$TotalSeconds"
        }
    },
    {
        "$sort": { "CreateTime": -1 }
    },
    {
        "$skip": 0
    },
    {
        "$limit": 1
    }
])
解释:

1、aggregate : 开启一个聚合查询;里面包含多个管道列表用 [ ] 包住;

每个管道用 {} 包裹;

2、$match:条件查询,只能出现一次,每个条件用 { }包裹;
 "$match": {
            "CreateTime": {
                "$gte": ISODate("2025-02-13T09:00:00Z"),
                "$lte": ISODate("2025-02-13T09:59:59Z")
            },
            "NeedStatisticsHourLog": true
        }

3、$group : 按属性分组

4、$project : 输出字段

5、$sort : 排序
6、$skip : 第几个开始取数据;
7、$limit :取几条数据



  db.getCollection("CatLitterBoxLog").find({
				"CreateTime": {
                "$gte": ISODate("2024-11-16T01:00:00Z"),
                "$lte": ISODate("2024-11-17T02:00:00Z")
            },
            "CatSinginId": {
						   "$ne" : 0 
						},
						"IotId":{
						   "$eq" :"tAqmC0OZEo6gUNqLLsVA000000"
						}}) 
						
						

db.getCollection("CatLitterBoxLog").aggregate([
    {
        "$match": {
            "CreateTime": {
                "$gte": ISODate("2024-11-16T01:00:00Z"),
                "$lte": ISODate("2024-11-17T02:00:00Z")
            },
            "CatSinginId": {
						   "$ne" : 0 
						} 
        }
    },
    {
        "$group": {
            "_id": {
                "CatSinginId":  "$CatSinginId",
								"IotId" : "$IotId"
            },
            "ParameterDic": { "$push": "$ParameterDic" } 
        }
    },
    {
        "$project": {
            "_id": 0,
            "IotId": "$_id.IotId",
            "CatSinginId": "$_id.CatSinginId",
            "ParameterDic": "$ParameterDic" 
        }
    },
    {
        "$sort": { "IotId": -1 ,"CatSinginId" : -1}
    },
    {
        "$skip": 1
    },
    {
        "$limit": 100
    }
])






















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值