【问题标题】:add condition to most recent values result将条件添加到最近的值结果
【发布时间】:2021-06-30 18:14:36
【问题描述】:

mongoplayground

我的结果包括“mostRecentValues”,我希望仅在它们不相同的情况下投影值。我的困难在于添加条件以仅显示两个值之间是否存在变化(在本例中为 mostRecentValues)。

my_coll.create_index([('car_id',1),('timestamp',-1)], unique=True)

【问题讨论】:

    标签: mongodb mongodb-query aggregate


    【解决方案1】:

    当操作涉及打开一个完整的文档时,请考虑 $group。将此添加到您的管道应该会为您指明正确的方向。

    (playground)

    db.collection.aggregate([
      {
        "$group": {
          _id: "cars",
          "cars": {
            "$push": {
              "$cond": [
                {
                  "$ne": [
                    {
                      "$arrayElemAt": [
                        "$mostRecentValues",
                        0
                      ]
                    },
                    {
                      "$arrayElemAt": [
                        "$mostRecentValues",
                        1
                      ]
                    }
                  ]
                },
                "$$ROOT",
                "$$REMOVE"
              ]
            }
          }
        }
      },
      {
        $unwind: "$cars"
      }
    ])
    

    如果每个文档只有 3 个字段,则可以添加:

      {
        $project: {
          car_id: "$cars.car_id",
          mostRecentTime: "$cars.mostRecentTime",
          mostRecentValues: "$cars.MostRecentValues"
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2019-05-28
      • 2016-04-04
      • 1970-01-01
      • 2022-10-25
      • 1970-01-01
      相关资源
      最近更新 更多