首页 > 解决方案 > 根据提供的键修改嵌套的 dict 字段

问题描述

我有以下三个不同的文件

{
  "category" : "aaaaa",
  "summary" : {
    "details" : {
      "city" : "abc"
      "year_of_reg" : "2012",
      "dept" : "dev"
    }
  }
}

{
  "category" : "bbbb",
  "summary" : {
    "details" : {
      "city" : "abc",
      "year_of_reg" : "2016",
      "dept" : "dev"
    }
  }
}

{
  "category" : "aaaaa",
  "summary" : {
    "details" : {
      "dept" : "ui",
      "year_of_reg" : "2018"
    }
  }
}

我将提供一组必需的键,摘要下的详细信息应该只有那些必需的键。应该弹出剩余的键

例如。如果我提供 city 和 year_of_reg 作为必需的键,这三个文件应该修改如下

{
  "category" : "aaaaa",
  "summary" : {
    "details" : {
      "city" : "abc"
      "year_of_reg" : "2012"
    }
  }
}

{
  "category" : "bbbb",
  "summary" : {
    "details" : {
      "city" : "abc",
      "year_of_reg" : "2016"
    }
  }
}

{
  "category" : "aaaaa",
  "summary" : {
    "details" : {
      "year_of_reg" : "2018"
    }
  }
}

如何做到这一点?

标签: mongodbaggregation-framework

解决方案


这应该可以帮助您:

const values = [ "city", "year_of_reg" ];

db.collection.aggregate({
    $addFields: {
        "summary.details": {
            $arrayToObject: { // transform modified array back to subdocument
                $filter: {
                    input: { $objectToArray: "$summary.details" }, // transform "summary.details" into a key-value pair representation
                    as: "this",
                    cond: {
                        $in: [ "$$this.k", values] // only keep the key-value pairs where the key is one of the strings you provide in the array
                    }
                }
            }
        }
    }
})

推荐阅读