【问题标题】:Is there a way to not $project keys that have an empty array in the mongodb aggregation pipeline?有没有办法在 mongodb 聚合管道中不使用具有空数组的 $project 键?
【发布时间】:2020-09-30 21:25:01
【问题描述】:

我得到一些 [] 值用于我返回的一些键结果,但我想这样做,以便根本不会返回具有 [] 值的键。这需要在聚合管道中。

例如:

{
"_id": "5e42fb9b74753bd02c86ca2c",
"key_one": 'something',
"key_two": 'another thing',
"key_three": [],
"key_four": [],
"key_five": 'one more time
}

我想要返回的东西:

{
 "_id": "5e42fb9b74753bd02c86ca2c",
"key_one": 'something',
"key_two": 'another thing',
"key_five": 'one more time
}

【问题讨论】:

    标签: python mongodb aggregation-framework projection eve


    【解决方案1】:

    如果字段为空数组,请使用 $project 阶段内的“$$REMOVE”变量删除字段。

    {
      $project: {
        key_three: {
          $cond: {
            if: {
              $ne: ["$key_three", []]
            },
            then: "$key_three",
            else: "$$REMOVE"
          }
        },
        key_four: {
          $cond: {
            if: {
              $ne: ["$key_four", []]
            },
            then: "$key_four",
            else: "$$REMOVE"
          }
        }
      }
    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多