我正在尝试这种聚合,但如何在此聚合中编写单个查询如何解决问题。请建议我。请给我两个文件switchID是一样的。但状态不同一个状态是:灯亮另一个状态是:灯亮。任何可能添加查询LIGHTS OFF avgduration - LIGHTS ON avgduration
db.lights.aggregate({
$match: {
CREATE_DATE: {
$gte: ISODate("2018-01-24T20:05:30.000Z"),
$lt: ISODate("2018-02-24T20:05:30.000Z")
}
}
}, {
$addFields: {
offduration: {
$divide: [{
$subtract: ["$RECEIVEDDATE", "$CREATE_DATE"]
}, 3600000]
}
}
}, {
"$group": {
_id: {
SWITCHID: "$SWITCHID",
STATUS: "$STATUS"
},
avgduration: {
$avg: "$offduration"
},
SWITCHID: {
$first: "$SWITCHID"
},
CREATE_DATE: {
$first: "$CREATE_DATE"
},
RECEIVEDDATE: {
$first: "$RECEIVEDDATE"
},
STATUS: {
$first: "$STATUS"
},
offduration: {
$first: "$offduration"
},
}
}, {
$project: {
_id: 1,
SWITCHID: 1,
CREATE_DATE: 1,
RECEIVEDDATE: 1,
STATUS: 1,
avgduration: '$avgduration',
offduration: '$offduration'
}
})
dblights.aggregate({"$group" : {
... _id: {
... SWITCHID: "$_id.SWITCHID"
... },
... on_minus_off: { $sum:{ "$cond": [
... { "$eq": [ "$_id.STATUS", "on" ] },
... "$avgduration",
... { $subtract: [ 0, "$avgduration" ] }
... ]}}
... }}
... ])