mongodb - 根据提供的键修改嵌套的 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"
}
}
}
如何做到这一点?
解决方案
这应该可以帮助您:
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
}
}
}
}
}
})
推荐阅读
- python - 如何修复 Python Gekko Max Equation Length 错误
- git - 用于提取给定年份报告文件(Excel 或 PDF)中源代码文件的每次提交之间的提交比较的 Git 代码
- three.js - 在threejs中使用顶点着色器旋转几何体
- visual-studio - 无法在文件系统中部署 dtsx 包 - VS 2019 社区,SSDT
- powershell - 无法仅在完成最终结果后才显示 Powershell 列表
- java - (SSL) 将私钥加载到 android 密钥库中
- spring-boot - 具有 OAuth2 身份验证的独立 SpringBoot 应用程序
- javascript - 手动关闭 getDisplayMedia 的原生屏幕选择器
- python - Groupby 创建列表
- javascript - 根据提交按钮启用或禁用表单验证