首页 > 解决方案 > 如何从数组内的对象中删除空字符串和数组?MongoDB 聚合

问题描述

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

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

标签: pythonmongodbmongodb-queryaggregation-frameworkeve

解决方案


如果要投影所有非空字符串或空数组的字段,请使用$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游乐场


推荐阅读