在下面的$aggregate
查询中,想要添加一个$gt
和$lt
mongo doc:
{
"_id" : ObjectId("599eb4fae0f86361c36b1c91"),
"device_id" : ObjectId("5993df1b9a5fea3183064e49"),
"updatedAt" : ISODate("2017-08-24T11:38:12.135Z"),
"power_data" : [
{
"timestamp" : ISODate("2017-08-24T11:14:04.256Z"),
"_id" : ObjectId("599eb4fdeea8c69622751de3"),
"pfactor" : 1,
"rpower" : 0,
"voltage" : 0,
"current" : 0,
"energy" : 0,
"power" : 0
},
{
"timestamp" : ISODate("2017-08-24T11:14:04.256Z"),
"_id" : ObjectId("599eb507eea8c69622751de4"),
"pfactor" : 1,
"rpower" : 0,
"voltage" : 0,
"current" : 0,
"energy" : 0,
"power" : 0
},
{
"timestamp" : ISODate("2017-08-24T11:14:04.256Z"),
"_id" : ObjectId("599eb511eea8c69622751de5"),
"pfactor" : 1,
"rpower" : 0,
"voltage" : 0,
"current" : 0,
"energy" : 0,
"power" : 0
},
],
"__v" : 0,
"createdAt" : ISODate("2017-08-24T11:14:05.946Z")
}
这是查询:
aggregate([{
$match: { "device_id": { $in: [ObjectId("5993df1b9a5fea3183064e49")] } }
}, {
$project: {
"power_data": 1
}
}, {
$unwind: "$power_data"
},
{
$project: {
"power": "$power_data.power", "hours": { $dayOfMonth: "$power_data.timestamp" }
}
}, {
$group: {
"_id": "$hours", "avg_power": { $avg: "$power" }
}
}]
所有我想要的是,通过传递一些日期时间戳范围,我将只得到这个时间间隔的数据,目前它的整体计算。
谢谢您宝贵的时间!
答案 0 :(得分:1)
我认为您只需在$match
之后添加额外的$unwind
阶段。
这是完整的管道:
{
$match: { "device_id": { $in: [ObjectId("5993df1b9a5fea3183064e49")] } }
},
{
$project: { "power_data": 1 }
},
{
$unwind: "$power_data"
},
{
$match: {
"power_data.timestamp" : { $gt : ISODate("2017-08-23T12:00:00.000Z"), $lt: ISODate("2017-08-25T12:00:00.000Z")}
}
},
{
$project: { "power": "$power_data.power", "hours": { $dayOfMonth: "$power_data.timestamp" }
}
},
{
$group: { "_id": "$hours", "avg_power": { $avg: "$power" } }
}