【问题标题】:Find two latest and oldest documents which containing specific field values查找包含特定字段值的两个最新和最旧的文档
【发布时间】:2021-01-17 18:00:29
【问题描述】:

技术: Mongoose、NodeJS、MongoDB

问题

以下文档将每 10 秒保存在 MongoDB 集群上。

{
  "_id": "6003fafc04cb3727e40812b2",
  "currentRound": 39300,
  "current": 4.131929,
  "voltage": 245.855,
  "power": 956.5797,
  "frequency": 50,
  "totalPower": 1167.862,
  "importPower": 1167.862,
  "exportPower": 0,
  "powerFactor": 0.998356,
  "rssi": -59,
  "deviceId": "EC:FA:BC:63:02:C1",
  "slaveId": 201,
  "timestamp": 1610873596543,
  "__v": 0
}

有两种类型的从属 ID(101、201)文档保存在同一个集合中,每个从属 ID 都有一个特定的设备 ID。我想使用昨天的时间戳(从上午 0:00 到晚上 11:59)检索最新和最旧的包含 101 和 201 的文档。

尝试

我尝试了以下解决方案。但distinct('slaveId') 仅返回不同的特定字段属性。

        const latestPGStats = await PGStat
            .find({
                deviceId: { $in: deviceIds },
                timestamp: { $lte: endTimestamp, $gte: startTimestamp }
            })
            .sort({ timestamp: -1 })
            .distinct('slaveId')
            .limit(2);

我看到一些人建议使用 mongo 聚合。但我对该领域一无所知。

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    你可以试试aggregate()

    • $match你的条件
    • $facet 分隔结果,第一个是最新的,第二个是最旧的
    • $sort timestamp 按降序排列
    • $group by slaveId 并获得 $first 最新文档和 $last 最旧文档
    • $limit` 获取单个文档
    const latestPGStats = await PGStat.aggregate([
      {
        $match: {
          deviceId: { $in: deviceIds },
          timestamp: { $lte: endTimestamp, $gte: startTimestamp }
        }
      },
      { $sort: { timestamp: -1 } },
      {
        $facet: {
          latest: [
            {
              $group: {
                _id: "$slaveId",
                root: { $first: "$$ROOT" }
              }
            },
            { $limit: 1 }
          ],
          oldest: [
            {
              $group: {
                _id: "$slaveId",
                root: { $last: "$$ROOT" }
              }
            },
            { $limit: 1 }
          ]
        }
      }
    ])
    

    【讨论】:

    • 完美!。这解决了我的问题。但我必须将限制添加为 2,因为我总是需要获取两个包含文档的不同从属 ID。非常感谢@turivishal
    猜你喜欢
    • 1970-01-01
    • 2019-12-11
    • 2018-04-21
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 2014-12-16
    • 2016-01-26
    • 2020-04-19
    相关资源
    最近更新 更多