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

How can I retrieve specific element from array using aggregation in Mongoose NodeJS

所以我有一个聚合代码

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]
]

但是代码returns这个

[
    [
        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 类型值。

  • $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