mongodb - 如何在mongodb的嵌套文档中查找记录
问题描述
这是 my_list 集合的示例记录,其中包含多级嵌套文档,如何从包含 3rd_party_setting 子记录和 with 的记录中找到对应的“key”值3rd_party_id="123456"
?即找到对应的键值3rd_party_setting.3rd_party_id ="123456"
[
{
"_id": 551,
"name": "demo1",
"groups": {
"123": {
"name": "group1",
"teams": {
"110": {
"name": "team1",
"team_id": "2322"
},
"111": {
"name": "team1",
"team_id": "2322"
}
},
"3rd_party_setting": {
"3rd_party_id": "123456",
"key": "this is the key",
"create_dt": "2020-02-06 01:27:19",
"update_dt": "2020-02-06 01:27:19"
}
}
}
},
{
"_id": 552,
"name": "demo2",
"groups": {
"124": {
"name": "group2",
"teams": {
"210": {
"name": "team1",
"team_id": "2322"
},
"211": {
"name": "team1",
"team_id": "2322"
}
},
"3rd_party_setting": {
"3rd_party_id": "123458",
"key": "this is the key2",
"create_dt": "2020-02-06 01:27:19",
"update_dt": "2020-02-06 01:27:19"
}
}
}
},
{
"_id": 555,
"name": "demo3",
"groups": {
"125": {
"name": "group3",
"teams": {
"310": {
"name": "team3",
"team_id": "2322"
},
"311": {
"name": "team3",
"team_id": "2322"
}
}
}
}
}
]
解决方案
您可以使用聚合获得您正在查看的内容。
这个聚合管道:
db.collection.aggregate([
{
$project: {
o: {
$objectToArray: "$groups"
}
}
},
{
$match: {
"o.v.3rd_party_setting.3rd_party_id": "123456"
}
},
{
$project: {
key: "$o.v.3rd_party_setting.key"
}
}
])
- 在字段上使用 $objectToArray 将
groups
其拆分为k
并v
检查内容,而不管键名如何 - 3rd_party_id 上的 $match
- $project 只返回所需的密钥
如果您有超过 1 个组的任何文档,您可能需要在匹配之前 $unwind。
样品操场
推荐阅读
- laravel - 为什么 Laravel 显示将我发送到错误的路线?
- vue.js - chart.js 如何为两个轴配置标签
- google-app-engine - GCP 负载均衡器上的 URL 正则表达式映射
- python - 连接列表时int对象不可迭代?
- list - 合并字典列表
- python - 教程 4 中的 Django 教程错误(/polls/1/ 处的操作错误)
- sql-update - 如何使用 Amazon Redshift 中的临时表列更新现有表中的列?
- javascript - 在浮动 div 中设置 CKEditor 5(Vue 组件)的高度
- sql - PostgreSQL - 在 JOIN 条件中不允许使用聚合函数
- php - 查询以显示基于最新日期的最新值