我从以下代码获得数据:
db.getCollection('lampus').aggregate([
{
$unwind: '$data'
},
{
$match: {_id: "sensor-2",
'data.tanggal': {
$gt: (new Date(new ISODate()-1*1000*60*60*24))
}
}
},
{
$sort: {
'data.tanggal': 1
}
},
])
结果是:
[{"_id":"sensor-2","data":{"sensor":
{"intensitas":3,"arus":0.05},"tanggal":"2018-08-05T14:05:58.757Z"}},
{"_id":"sensor-2","data":{"sensor":
{"intensitas":11,"arus":0.05},"tanggal":"2018-08-05T14:05:58.756Z"}},
{"_id":"sensor-2","data":{"sensor":
{"intensitas":8,"arus":0.05},"tanggal":"2018-08-05T14:05:52.654Z"}},
{"_id":"sensor-2","data":{"sensor":
{"intensitas":13,"arus":0.05},"tanggal":"2018-08-05T14:05:51.152Z"}},
{"_id":"sensor-2","data":{"sensor":
{"intensitas":15,"arus":0.05},"tanggal":"2018-08-05T14:05:46.651Z"}},
{"_id":"sensor-2","data":{"sensor":
{"intensitas":13,"arus":0.1},"tanggal":"2018-08-04T14:05:45.150Z"}}]
“ _ id:sensor-2”太多,因为上面的代码中$ unwind操作。 任务是: 1.有一个“ intensitas”值,如何从所有对象中平均所有“ intensitas”? 2.我如何实现对NodeJ的查询,因为那是mongodb中的“ ISODate”格式,因为当我尝试在nodeJ中使用“ ISODate未定义”时。
答案 0 :(得分:0)
1-您可以使用$ group中可用的$ avg,而$ group中的ID为空。 ($ avg在$ project中也可用)
答案 1 :(得分:0)
最后我可以做我想做的,我使用这段代码:
db.getCollection('lampus').aggregate([
{
$unwind: '$data'
},
{
$match: {_id: "sensor-2",
'data.tanggal': {
$gt: (new Date(new ISODate()-1*1000*60*60*24))
}
}
},
{
$sort: {
'data.tanggal': 1
}
},
{
$group:
{
_id: "$_id",
RataInten: { $avg: { $multiply: [ "$data.sensor.intensitas" ] } },
RataArus: { $avg: { $multiply: [ "$data.sensor.arus" ] } },
}
},
{$project: {data:[{arus :"$RataArus",intensitas :"$RataInten"}]}},
{ $out : "3hari" },
])
在{$ out:“ 3hari”}上,即创建名为“ 3hari”的集合tha的新内容,
{
"_id" : "sensor-2",
"data" : [
{
"arus" : 0.1,
"intensitas" : 5.0,
"today" : ISODate("2018-08-05T15:08:17.513+07:00")
}
]
}
这就是我想要的,但是我遇到了问题,我需要更多的“数据”数组,就像我期望的那样:
{
"_id" : "sensor-2",
"data" : [
{
"arus" : 0.1,
"intensitas" : 5.0,
"today" : ISODate("2018-08-05T15:08:17.513+07:00")
},
{
"arus" : 0.1,
"intensitas" : 8.0,
"today" : ISODate("2018-08-08T15:08:17.513+07:00")
},
{
"arus" : 0.1,
"intensitas" : 9.0,
"today" : ISODate("2018-08-12T15:08:17.513+07:00")
}
]
}
是的,我需要更新数据数组,并且具有更多数组...