【问题标题】:How to remove empty string and arrays from objects inside an array? MongoDB Aggegation如何从数组内的对象中删除空字符串和数组? MongoDB聚合
【发布时间】:2020-10-15 00:58:39
【问题描述】:

我想删除文档中的空字符串和空数组。有没有办法使用 MongoDB 聚合框架来做到这一点?以下是传入文档的示例:

"item": [{
    "array_objects":[{
        "text": '',
        "second_text": '',
        "empty_array": [],
        "empty_array_2":[],
    }]
}]

【问题讨论】:

    标签: python mongodb mongodb-query aggregation-framework eve


    【解决方案1】:

    如果要投影所有非空字符串或空数组的字段,请使用$filter

    您可以尝试以下聚合查询:

    db.collection.aggregate([
      {
        $unwind: "$item"
      },
      {
        $unwind: "$item.array_objects"
      },
      {
        $project: {
          item: {
            $arrayToObject: {
              $filter: {
                input: {
                  $objectToArray: "$item.array_objects"
                },
                cond: {
                  $and: [
                    {
                      $ne: [
                        "$$this.v",
                        ""
                      ]
                    },
                    {
                      $ne: [
                        "$$this.v",
                        []
                      ]
                    }
                  ]
                }
              }
            }
          }
        }
      }
    ])
    

    MongoDB playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-27
      • 2022-08-05
      • 2021-01-04
      • 2020-02-01
      • 2015-02-14
      • 1970-01-01
      • 2018-04-20
      相关资源
      最近更新 更多