根据提供的键修改嵌套的dict字段

时间:2018-08-14 13:10:20

标签: mongodb aggregation-framework

我有以下三个不同的文件

{
  "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"
    }
  }
}

如何实现?

1 个答案:

答案 0 :(得分:1)

这应该可以帮助您:

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
                    }
                }
            }
        }
    }
})