我在该查询中创建了一个查询,我使用$ unwind多个字段。查询响应没问题,但我的高级建议我这是错误的查询。因为查询响应格式不正确,而不是r_y_b_phasetimestamp时间戳的升序。我给出了如下查询:
db.energy.aggregate([
{
$project: { EventTS: 1, RPhaseVoltage: 1, YPhaseVoltage:1, BPhaseVoltage:1}
},
{
$unwind: {
path: "$RPhaseVoltage",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$unwind: {
path: "$YPhaseVoltage",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$unwind: {
path: "$BPhaseVoltage",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$match: {
$and: [
{RPhaseVoltage: {$ne: null}},
{YPhaseVoltage: {$ne: null}},
{BPhaseVoltage: {$ne: null}},
]
}
},
{
$project: {
_id:0,
EventTS:1,
RPhaseVoltage: 1,
YPhaseVoltage: 1,
BPhaseVoltage:1,
r_y_b_phasetimestamp: {
"$add": [
{ "$subtract": ["$EventTS", new Date("1970-01-01")]},
{ "$multiply": [ 60000, "$arrayIndex" ] }
]
}
}
},
{
$project: {
"rvoltage_data":["$r_y_b_phasetimestamp", "$RPhaseVoltage"],
"yvoltage_data":["$r_y_b_phasetimestamp", "$YPhaseVoltage"],
"bvoltage_data":["$r_y_b_phasetimestamp", "$BPhaseVoltage"]
}
},
{
$sort:{
r_y_b_phasetimestamp:-1
}
}
]);
我的收集样本如下
{
"_id" : ObjectId("57742e0f8d8b8fdf278b45d1"),
"EventTS" : ISODate("2016-06-24T12:30:00.000+0000"),
"RPhaseVoltage" : [
null,
231.81,
231.81,
null,
231.42
],
"YPhaseVoltage" : [
229.95,
229.95,
null,
null,
231.32
],
"BPhaseVoltage" : [
null,
231.44,
231.44,
null,
null
]
}
我的图表输出链接是Graph Plotting Link。这个查询我用于图形绘图。请建议我,我的查询是错误的,为什么图表正在绘制这个
答案 0 :(得分:0)
您正在使用$project
2次。当您使用$project
时,只有投影值会传递到管道的下一部分。在使用排序之前,您不会预测r_y_b_phasetimestamp
。因此,排序时将不确定r_y_b_phasetimestamp
,并导致未排序的结果。尝试在r_y_b_phasetimestamp:"$r_y_b_phasetimestamp"
之后传递"bvoltage_data":["$r_y_b_phasetimestamp", "$BPhaseVoltage"]
。所以最终的代码是
db.energy.aggregate([
{
$project: { EventTS: 1, RPhaseVoltage: 1, YPhaseVoltage:1, BPhaseVoltage:1}
},
{
$unwind: {
path: "$RPhaseVoltage",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$unwind: {
path: "$YPhaseVoltage",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$unwind: {
path: "$BPhaseVoltage",
includeArrayIndex: "arrayIndex",
preserveNullAndEmptyArrays: true
}
},
{
$match: {
$and: [
{RPhaseVoltage: {$ne: null}},
{YPhaseVoltage: {$ne: null}},
{BPhaseVoltage: {$ne: null}},
]
}
},
{
$project: {
_id:0,
EventTS:1,
RPhaseVoltage: 1,
YPhaseVoltage: 1,
BPhaseVoltage:1,
r_y_b_phasetimestamp: {
"$add": [
{ "$subtract": ["$EventTS", new Date("1970-01-01")]},
{ "$multiply": [ 60000, "$arrayIndex" ] }
]
}
}
},
{
$project: {
"rvoltage_data":["$r_y_b_phasetimestamp", "$RPhaseVoltage"],
"yvoltage_data":["$r_y_b_phasetimestamp", "$YPhaseVoltage"],
"bvoltage_data":["$r_y_b_phasetimestamp", "$BPhaseVoltage"],
r_y_b_phasetimestamp:"$r_y_b_phasetimestamp"
}
},
{
$sort:{
r_y_b_phasetimestamp:-1
}
}
]);