json - 在 MongoDB 中查询嵌套的 JSON
问题描述
所以我在 MongoDB 数据库中有以下嵌套集合:
{'_id': ObjectId('615e9b8d17fa084f2e8d4b83'),
'status': 'Played',
'roundId': 4165363,
'gameweek': 2,
'teamsData': {'12274': {'scoreET': 0,
'coachId': 89543,
'side': 'home',
'teamId': 12274,
'score': 0,
'scoreP': 0,
'hasFormation': 1,
'formation': {'bench': [{'playerId': 101652,
'assists': '0',
'goals': 'null',
'ownGoals': '0',
'redCards': '0',
'yellowCards': '0'},
....
{'playerId': 90991,
'assists': '0',
'goals': 'null',
'ownGoals': '0',
'redCards': '0',
'yellowCards': '0'},
'9598': {'scoreET': 0,
'coachId': 122788,
'side': 'away',
'teamId': 9598,
'score': 3,
'scoreP': 0,
'hasFormation': 1,
'formation': {'bench': [{'playerId': 69964,
'assists': '0',
'goals': 'null',
'ownGoals': '0',
'redCards': '0',
'yellowCards': '0'},
....
'lineup': [{'playerId': 69616,
'assists': '0',
'goals': '1',
'ownGoals': '0',
'redCards': '0',
'yellowCards': '39'}
我想要一个playerId和目标列表,我知道我可以投射类似的东西
list(db.matches.find({},
projection = ['teamsData.9598.formation.lineup.playerId', 'teamsData.9598.formation.lineup.goals']))
这会给我带来
[{'_id': ObjectId('615e9b8d17fa084f2e8d4b83'),
'teamsData': {'9598': {'formation': {'lineup': [{'playerId': 69616, 'goals': '1'},
{'playerId': 14812, 'goals': 'null'},
{'playerId': 69409, 'goals': 'null'},
{'playerId': 25393, 'goals': 'null'},
{'playerId': 135747, 'goals': 'null'},
{'playerId': 3476, 'goals': '1'},
{'playerId': 105361, 'goals': 'null'},
{'playerId': 8287, 'goals': '1'},
{'playerId': 69396, 'goals': 'null'},
{'playerId': 69968, 'goals': 'null'},
{'playerId': 14943, 'goals': '0'}]}}}}]
问题是我不想在项目代码中写下9598部分(然后是每个 teamId),否则我将无法在整个集合中扩展它。有谁知道如何获取所有团队的 playerId 和目标?
我读了几个关于嵌套 JSON 的问题,但没有一个像这样的结构,所以我很感激任何帮助。谢谢 :)
解决方案
询问
- 对于所有文档和所有团队密钥
- 给出每个团队的 playerId 和目标列表
- 将对象转换为数组
$map
在成员上,只保留团队密钥,只保留 playerId 和目标
*我不知道你真正想要什么,但也许这会有所帮助。
*如果你想要一个特定的团队密钥,你可以过滤数组$filter
aggregate(
[{"$project":
{"teamsData":
{"$map":
{"input": {"$objectToArray": "$teamsData"},
"in":
{"$mergeObjects":
[{"teamId": "$$this.k"},
{"players-goals":
{"$map":
{"input": "$$this.v.formation.lineup",
"in": {"playerId": "$$t.playerId", "goals": "$$t.goals"},
"as": "t"}}}]}}}}}])
推荐阅读
- python - 无法更改字典元素
- c# - 用于获取远程文件大小的 Httpclient MethodNotAllowed 405
- web-component - 模板配置在 dist 中生成的文件不能独立工作
- python-3.x - 使用 Django 根据用户选择的另一个对象属性的值来过滤属性的对象值
- javascript - 为什么 javascript 代码不适用于 svg 对象?
- flutter - 为什么我们在颤动中导航到下一个屏幕时传递上下文?
- python-3.x - 在python中使用pandas访问数据透视表中的多索引值
- python-3.x - 当 if_exists='replace' 时,pandas to_sql 函数不起作用
- apache-kafka - Kafka Consumer 偏移提交检查以避免提交较小的偏移
- javascript - shopify上带有单独链接的随机横幅