【问题标题】:How can I retrieve specific element from array using aggregation in Mongoose NodeJS如何在 Mongoose NodeJS 中使用聚合从数组中检索特定元素
【发布时间】:2021-06-15 17:26:01
【问题描述】:

所以我有一个聚合代码

const documents = await deviceCollection
  .aggregate([
    {
      $match: {
        'readings.t': sensorType,
      },
    },
    { $unwind: '$readings' },
    {
      $project: {
        _id: 0,
        data: ['$readings.r', '$created_at'],
      },
    },
  ])
  .toArray();

return documents.map(({ data }) => data);

我有一个像这样的文档结构

{
    "readings" : [ 
        {
            "t" : "temperature",
            "r" : 6
        }, 
        {
            "t" : "humidity",
            "r" : 66
        }
    ],
    "created_at" : ISODate("2021-02-24T09:45:09.858Z"),
    "updated_at" : ISODate("2021-02-24T09:45:09.858Z")
}

我需要将日期范围内特定阅读类型的 r 值和 created_at 聚合为 UTC 数字。 例如,temperature 读数的预期输出为:

[
 [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"
    ],
]

这意味着我也得到了humidity 类型值。

【问题讨论】:

    标签: node.js mongoose aggregation-framework aggregate-functions aggregation


    【解决方案1】:
    • $match你的情况
    • $unwind解构readings数组
    • $match 再次过滤readings 对象
    • $toLong 将 ISO 日期格式转换为时间戳
    • $group by null 并在单个数组中构造readings 数组
    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 : [];
    

    Playground

    【讨论】:

    • 谢谢,效果很好,但是当我在匹配运算符中添加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" }`
    • 您必须将该日期转换为日期类型以匹配created_at: { $gte: new Date(start_date), $lte: new Date(end_date) }
    猜你喜欢
    • 2020-10-29
    • 2022-10-12
    • 2019-04-19
    • 2020-03-14
    • 2020-03-22
    • 2017-04-24
    • 1970-01-01
    • 2016-02-24
    • 2021-12-29
    相关资源
    最近更新 更多