【问题标题】:How to remove empty string and arrays from objects inside an object with the mongodb aggregation pipeline?如何使用 mongodb 聚合管道从对象内的对象中删除空字符串和数组?
【发布时间】:2020-10-15 12:53:15
【问题描述】:

我想从对象中的对象中删除任何具有空 text 字符串的文档。有没有办法使用 MongoDB 聚合框架来做到这一点?在这种情况下,它将是 object_1object_2 中的 text

"array_of_objects":[{
    "city": "Seattle",
    "array_1": [],
    "object_1":{
        "name": "Mandy",
        "text" "",
    },
    "object_2":{
        "name": "Billy",
        "text" "",
    },
}]

【问题讨论】:

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


    【解决方案1】:

    如果要投影所有不包含空 text 字符串的字段,请使用以下查询。

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

    MongoDB Playground

    如果你想投影所有没有空text字符串和空数组的字段,只需添加一个$ne空数组检查,使用以下查询:

    MongoDB Playground

    如果要删除任何包含空文本字符串的文档,请使用额外的 $match 阶段来删除包含空文本字符串的文档。

    db.collection.aggregate([
      {
        $unwind: "$array_of_objects"
      },
      {
        $project: {
          array_of_objects: {
            $filter: {
              input: {
                $objectToArray: "$array_of_objects"
              },
              cond: {
                $and: [
                  {
                    $ne: [
                      "$$this.v.text",
                      ""
                    ]
                  },
                  {
                    $ne: [
                      "$$this.v",
                      []
                    ]
                  }
                ]
              }
            }
          }
        }
      },
      {
        $match: {
          "array_of_objects.v.text": {
            $exists: true
          }
        }
      },
      {
        $project: {
          array_of_objects: {
            "$arrayToObject": "$array_of_objects"
          }
        }
      }
    ])
    

    MongoDB Playground

    【讨论】:

      【解决方案2】:

      你可以使用$pull操作符来移除text字段为空的子文档-

      var query = {};
      var update = {
          $pull: {
              array_of_objects: {
                  'object_1.text': '',
                  'object_2.text': ''
              }
          }
      };
      var options = {
          multi: true
      };
      
      db.collection.update(query, update, options);
      

      【讨论】:

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