首页 > 解决方案 > 寻求帮助——查询 MongoDB

问题描述

我对 MongoDB 很陌生,我正在尝试查询我导入的一些数据。我昨天和今天试了几个小时,在我的理解上有所进步,但仍然没有任何结果。我尝试从博客、stackoverflow、youtube 甚至 MongoDB 网站一步一步地跟踪事情,但仍然无法正确地将其转换为我的数据。我希望有人能指出我正确的方向,而不是找人为我编写代码。这是我正在烹饪的东西:

数据片段:

{'_id': ObjectId('608dd1a2abf9c97d8d771c41'),
 'competition': {'area': {'id': 2072, 'name': 'England'},
                 'code': 'PL',
                 'id': 2021,
                 'lastUpdated': '2021-04-17T02:20:14Z',
                 'name': 'Premier League',
                 'plan': 'TIER_ONE'},
 'filters': {},
 'season': {'currentMatchday': 34,
            'endDate': '2021-05-23',
            'id': 619,
            'startDate': '2020-09-12',
            'winner': None},
 'standings': [{'group': None,
                'stage': 'REGULAR_SEASON',
                'table': [{'draw': 5,
                           'form': 'W,W,L,W,W',
                           'goalDifference': 47,
                           'goalsAgainst': 24,
                           'goalsFor': 71,
                           'lost': 4,
                           'playedGames': 34,
                           'points': 80,
                           'position': 1,
                           'team': {'crestUrl': 'https://crests.football-data.org/65.svg',
                                    'id': 65,
                                    'name': 'Manchester City FC'},
                           'won': 25}}

我想要实现的目标:我试图查询standings.table.team.name 但没有成功。我退后一步,开始专注于查询 Competition.name。

我尝试过的:我使用 Python 使用以下查询尝试的一些(不是全部)事情:

db.standings.find_one( {'standings.table.team.name': "Manchester City FC"})
db.standings.find_one( {'standings.table.team.name': 'Manchester City FC'}) 
db.standings.find_one( {'competition.name': "Premier League"})
db.standings.find_one( {"competition.name": 'Premier League'})
db.standings.find_one( {'competition.name': 'Premier League'})
db.standings.find_one( {"competition.name": "Premier League"})

-- 我这里的所有结果都返回数据库中的所有数据。

在 MongoDB Compass UI 中进行的尝试:

我也在 Mongo Shell 中尝试过,但我上面使用的语法几乎是我在 shell 中不断重复的,但仍然没有运气。

对于我在这里缺少的内容,我可以获得任何帮助或指示吗?我确实尝试过研究并尝试不同的变化和组合,但仍然没有得到任何东西。

标签: mongodbmongodb-querypymongo-3.x

解决方案


如果我理解正确,您只想接收查询的选定键/值。你能证实这一点吗?在这种情况下,请尝试参考findOne的文档——您需要定义投影,即您想要返回的字段,否则您将获得所有字段(如果过滤器不合适,则什么也没有)。

我想你正在使用 PyMongo。请参阅此处获取文档, find_one似乎使用与find.

也许您可以尝试类似的方法db.standings.find_one( {'competition.name': 'Premier League'}, {'competition.name': 1}) - 这应该返回一个与过滤器匹配并包含该competition.name字段的对象。


推荐阅读