【发布时间】:2020-06-24 18:39:32
【问题描述】:
假设我的 MongoDB 集合中有以下文档,我如何检索 fixtures 中键的值,这样如果我使用 1 的限制,则只能获取 fixtures 中的第一个对象,如果我将其限制为2,它会同时出现在第一个文档和第二个文档中。
我正在寻找的输出是一个管道,它从数组中返回键、值对,例如以 dict 的形式返回 fixtures。
#Example
collection.find({}, {'fixtures':1, '_id': 0}).limit(1)
>>>{'fixtures': [{'away_team': 'Arsenal',
'away_team_id': 1,
'away_team_score': 1,
'away_team_shortName': 'Arsenal',
'home_team': 'Newcastle United',
'home_team_id': 23,
'home_team_score': 0,
'home_team_shortName': 'Newcastle',
}]}
#The output I want
>>>{'away_team': 'Arsenal',
'away_team_id': 1,
'away_team_score': 1,
'away_team_shortName': 'Arsenal',
'home_team': 'Newcastle United',
'home_team_id': 23,
'home_team_score': 0,
'home_team_shortName': 'Newcastle',
}
如何使用find() 或aggregate() 存档。我知道find({}, {'fixtures.KEY': 1}),但它返回以下难以使用的数据结构:
fixtures:[{KEY: value}]
{
"team": "Arsenal",
"team_id": 1,
"team_shortName": "Arsenal",
"competition": "Premier League",
"competition_abbr": "EN_PR",
"competition_id": 1,
"season_label": "2019/20",
"season_id": 274,
"fixtures": [
{
"home_team": "Brighton and Hove Albion",
"home_team_id": 131,
"home_team_shortName": "Brighton",
"home_team_score": 2,
"away_team": "Arsenal",
"away_team_id": 1,
"away_team_shortName": "Arsenal",
"away_team_score": 1,
},
{
"home_team": "Manchester City",
"home_team_id": 11,
"home_team_shortName": "Man City",
"home_team_score": 3,
"away_team": "Arsenal",
"away_team_id": 1,
"away_team_shortName": "Arsenal",
"away_team_score": 0,
}
]
},
{
"team": "Arsenal",
"team_id": 1,
"team_shortName": "Arsenal",
"competition": "Premier League",
"competition_abbr": "EN_PR",
"competition_id": 1,
"season_label": "2019/20",
"season_id": 274,
"fixtures": [
{
"home_team": "Arsenal",
"home_team_id": 1,
"home_team_shortName": "Arsenal",
"home_team_score": 3,
"away_team": "Everton",
"away_team_id": 7,
"away_team_shortName": "Everton",
"away_team_score": 2,
}
]
},
【问题讨论】:
-
我仍然不太清楚输出应该是什么样子,您能否也包括一个示例输出?
-
@thammada.ts 谢谢你的意见,现在清楚了吗?
-
那么您希望数组字段
fixtures的第一个元素作为结果的根文档吗?或者数组索引 X 处的元素,您可以在其中指定 X? -
@thammada.ts 很抱歉造成混乱,我更新了预期输出以进行澄清
标签: python mongodb mongodb-query aggregation-framework