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
}
])