Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何使用Mongoose NodeJS中的聚合从数组中检索特定元素_Node.js_Mongoose_Aggregation Framework_Aggregate Functions_Aggregation - Fatal编程技术网

Node.js 如何使用Mongoose NodeJS中的聚合从数组中检索特定元素

Node.js 如何使用Mongoose NodeJS中的聚合从数组中检索特定元素,node.js,mongoose,aggregation-framework,aggregate-functions,aggregation,Node.js,Mongoose,Aggregation Framework,Aggregate Functions,Aggregation,所以我有一个聚合代码 const documents=wait deviceCollection .合计([ { $match:{ “readings.t”:传感器类型, }, }, {$unwind:'$READERS'}, { $项目:{ _id:0, 数据:['$reads.r','$created_at'], }, }, ]) .toArray(); 返回文档.map({data})=>data); 我有一个这样的文档结构 { “阅读资料”:[ { “t”:“温度”, “r”:6 },

所以我有一个聚合代码

const documents=wait deviceCollection
.合计([
{
$match:{
“readings.t”:传感器类型,
},
},
{$unwind:'$READERS'},
{
$项目:{
_id:0,
数据:['$reads.r','$created_at'],
},
},
])
.toArray();
返回文档.map({data})=>data);
我有一个这样的文档结构

{
“阅读资料”:[
{
“t”:“温度”,
“r”:6
}, 
{
“t”:“湿度”,
“r”:66
}
],
“创建时间”:ISODate(“2021-02-24T09:45:09.858Z”),
“更新时间”:ISODate(“2021-02-24T09:45:09.858Z”)
}
我需要将
r
值和
created_在
作为
UTC
日期范围内特定读取类型的编号进行聚合。 例如,
温度
读数的预期输出为:

[
[6, 1616061903204],
[5.6, 1616061903204]
]
但是代码返回这个

[
[
6.
“2021-02-24T09:45:09.858Z”
],
[
66,
“2021-02-24T09:45:09.858Z”
],
[
5.6,
“2021-02-24T09:50:09.820Z”
],
[
68,
“2021-02-24T09:50:09.820Z”
],
]
这意味着我也得到了湿度的类型值。

  • $match
    您的条件
  • $展开
    解构
    读数
    数组
  • $match
    再次过滤
    读数
    对象
  • $toLong
    将ISO日期格式转换为时间戳
  • $group
    按null排序,并在单个数组中构造
    读数
    数组

谢谢,它工作得很好,但是当我在match操作符中添加
created_at:{$gte:start_date,$lte:end_date},
时,出于某种原因,我收到一个空数组来自请求有效负载`“date_range”:{“start_date”:“2021-02-24T09:45:09.858Z”,“end_date”:“2021-02-24T10:05:09.804Z”}`您必须将该日期转换为match
created_中的日期类型:{$gte:new date(start_date),$lte:new date(end_date)}
const documents = await deviceCollection.aggregate([
  { $match: { "readings.t": sensorType } },
  { $unwind: "$readings" },
  { $match: { "readings.t": sensorType } },
  {
    $project: {
      readings: [
        "$readings.r",
        { $toLong: "$created_at" }
      ]
    }
  },
  {
    $group: {
      _id: null,
      readings: { $push: "$readings" }
    }
  }
]).toArray();

return documents.length ? documents[0].readings : [];