如何通过在数组中搜索值来查询文档?



以下面三个文档为例

[
{
_id: '/players/c/cruzne02.shtml',
url: '/players/c/cruzne02.shtml',
name: 'Nelson Cruz',
image: 'https://www.baseball-reference.com/req/202108020/images/headshots/f/fea2f131_mlbam.jpg',
teams: {
MIL: [ 2005 ],
TEX: [
2006, 2007, 2007, 2008,
2008, 2009, 2009, 2010,
2010, 2011, 2011, 2012,
2012, 2013, 2013
],
BAL: [ 2014 ],
SEA: [
2015, 2016,
2016, 2017,
2017, 2018,
2018
],
MIN: [ 2019, 2020, 2020, 2021, 2021 ],
TBR: [ 2021 ]
}
},
{
_id: '/players/b/berrijo01.shtml',
url: '/players/b/berrijo01.shtml',
name: 'Jose Berrios',
image: 'https://www.baseball-reference.com/req/202108020/images/headshots/d/d94db113_mlbam.jpg',
teams: {
MIN: [
2016, 2017, 2017,
2018, 2018, 2019,
2019, 2020, 2020,
2021, 2021
],
TOR: [ 2021 ]
}
},
{
_id: '/players/m/mauerjo01.shtml',
url: '/players/m/mauerjo01.shtml',
name: 'Joe Mauer',
image: 'https://www.baseball-reference.com/req/202108020/images/headshots/4/43c69595_mlbam.jpg',
teams: {
MIN: [
2004, 2005, 2005, 2006, 2006,
2007, 2007, 2008, 2008, 2009,
2009, 2010, 2010, 2011, 2011,
2012, 2012, 2013, 2013, 2014,
2014, 2015, 2015, 2016, 2016,
2017, 2017, 2018, 2018
]
}
}
]

例如,如果我想查询在2016年为MIN队效力的人,我想获得第二个和第三个文档。但是,如果我在MIN数组中查询2020,我会得到返回的第一个和第二个文档。我想从某支球队得到那年的球员,我不确定如何组织我的发现来得到我想要的结果。

我试过使用

db.Players.find({teams:{MIN: {$elemMatch: 2021}}});

但是它没有返回任何东西。我是否使用了$elemMatch错误?

teams字段是一个对象而不是一个数组,我认为这就是为什么$elemMatch不工作,因为它是一个数组操作符。

如果您想使用$elemMatch,您可以尝试这样的查询,它指定teams.MIN,这是一个数组:

db.Players.find({ "teams.MIN" : { $elemMatch: { $eq: 2021 }}});

但是因为这是一个具有单一查询条件的$elemMatch示例,所以这样做会更简单:

db.Players.find({ "teams.MIN" : 2021 });

最新更新