我正在尝试编写聚合总平均持续时间 我得到了输出但没有到达所有领域。 如何获得结果中的所有字段?
任何人请建议我。
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: 0,
SWITCHID: 1,
CREATE_DATE: 1,
RECEIVEDDATE: 1,
STATUS: 1,
avgduration: '$avgduration',
offduration: '$offduration'
} },
{"$group" : {
_id: { SWITCHID: "$SWITCHID" },
on_minus_off: {
$sum:{ "$cond": [
{ "$eq": ["$STATUS", "LIGHTS OFF"] },
"$avgduration",
{ $subtract: [ 0, "$avgduration" ] }
]
}
}
}
}
)
答案 0 :(得分:1)
您想为第一个管道中的必填字段添加"$project"
。那么你想在$group
这样的管道中应用,
$project: { requireFiled1 : "$requireFiled1", requireFiled2 : "$requireFiled2", }
//在$ group
中添加以下内容requiredField1 : { $first: "$requiredField1" // Projected Name in Projection Section },
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: 0,
SWITCHID: 1,
CREATE_DATE: 1,
RECEIVEDDATE: 1,
STATUS: 1,
avgduration: '$avgduration',
offduration: '$offduration'
}
},
{
"$group": {
_id: {
SWITCHID: "$SWITCHID"
},
requireFiled1 : {
$first: "$requireFiled1"
},
on_minus_off: {
$sum: {
"$cond": [
{
"$eq": [
"$STATUS",
"LIGHTS OFF"
]
},
"$avgduration",
{
$subtract: [
0,
"$avgduration"
]
}
]
}
}
}
})