簡體   English   中英

如何使用 mongodb 聚合管道從對象內的對象中刪除空字符串和數組?

[英]How to remove empty string and arrays from objects inside an object with the mongodb aggregation pipeline?

我想從對象內的對象中刪除任何具有空text字符串的文檔。 有沒有辦法用 MongoDB 聚合框架來做到這一點? 在這種情況下,它將是object_1object_2text

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

如果要投影所有沒有空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 游樂場

如果要投影所有沒有空text字符串和空數組的字段,只需添加一個$ne空數組檢查,使用以下查詢:

MongoDB 游樂場

如果要刪除任何具有空文本字符串的文檔,請使用額外的 $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 游樂場

您可以使用$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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM