mongodb - 在 MongoDB 中的记录中取消嵌套值
问题描述
我的任务是取消 中的记录MongoDB
,但不幸的是,我没有MongoDB
技能。
我有以下格式的记录:
{
"_id" : ObjectId("Some ID"),
"reason" : "Parameter: (artifact_id) is mandatory",
"timestamp_utc" : ISODate("2019-09-20T14:30:41.943Z"),
"timestamp" : ISODate("2019-09-20T07:30:41.943Z"),
"eventType" : "Some_Event",
"clientID" : "24839961",
"time_bucket" : [
"2019-year",
"2019-09-month",
"2019-37-week",
"2019-09-20-day",
"2019-09-20 07-hour"
],
"payload" : {
"resWidth" : 1440,
"resHeight" : 900,
"device" : "",
"context_eid" : "Some EID",
"artifact_revision_id" : 8389171,
"page_url" : "Some URL",
"client_ip" : "Some IP",
"tz" : "Asia/Calcutta",
"memberID" : Some_ID,
"url_referrer" : "Some_URL",
"tabID" : "Some ID",
"artifactID" : 5665946,
"visitorID" : "Some ID",
"g_event_id" : "Some ID",
"content_data" : "Some Data",
"sessionID" : "Some ID",
"user_agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"
},
"resolved" : false
}
请注意,这payload
是它自己的字典。我必须取消嵌套该字典并将其恢复到与文档中其他键相同的级别。像这样:
{
"_id" : ObjectId("Some ID"),
"reason" : "Parameter: (artifact_id) is mandatory",
"timestamp_utc" : ISODate("2019-09-20T14:30:41.943Z"),
"timestamp" : ISODate("2019-09-20T07:30:41.943Z"),
"eventType" : "Some_Event",
"clientID" : "24839961",
"time_bucket" : [
"2019-year",
"2019-09-month",
"2019-37-week",
"2019-09-20-day",
"2019-09-20 07-hour"
],
"resWidth" : 1440,
"resHeight" : 900,
"device" : "",
"context_eid" : "Some EID",
"artifact_revision_id" : 8389171,
"page_url" : "Some URL",
"client_ip" : "Some IP",
"tz" : "Asia/Calcutta",
"memberID" : Some_ID,
"url_referrer" : "Some_URL",
"tabID" : "Some ID",
"artifactID" : 5665946,
"visitorID" : "Some ID",
"g_event_id" : "Some ID",
"content_data" : "Some Data",
"sessionID" : "Some ID",
"user_agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36",
"resolved" : false
}
我最初的研究表明$reduce
可能是一种选择,但我似乎无法弄清楚。
对此主题的任何帮助将不胜感激。如果这个任务太简单而无法发布,我很抱歉,但我的MongoDB
技能为零。
解决方案
您可以使用MongoDB 聚合。如果我们将顶级文档($$ROOT
变量)与payload
对象合并,我们会得到单个对象($mergeObjects
应该分配给新变量,但我们减少了使用$ReplaceRoot
or进行 2 操作的管道步骤$ReplaceWith
)。
db.EVENT_NAME.aggregate([
{
$replaceRoot: {
newRoot: {
$mergeObjects: [
"$$ROOT",
"$payload"
]
}
}
},
{
$unset: "payload"
}
])
推荐阅读
- google-sheets - 仅使用某个组的值的饼图
- jquery - 我的 Rock, Pape, Scissors JQuery 代码不合逻辑
- r - xml转数据框时出现“无法找到函数的继承方法”错误如何解决?
- rust - 箱子名称有破折号:未解决的导入错误
- python - pytorch conv2d 值无法转换为 uint8_t 类型而不溢出
- python - 如何将 CSV 转换为 JSON-Python
- java - 如何使用 mouseEvent() 知道鼠标是否处于特定颜色
- python - Odoo v11 和 PyCharm 的问题
- python - python子进程不会像终端那样交错stderr和stdout
- laravel - 未定义索引:标题 laravel 6.0