0

So using the three documents below as examples

[
  {
    _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
      ]
    }
  }
]

For example if I want to query for someone who played for team MIN in 2016 I want to get the second and third document. But if I queried for 2020 in the MIN array I would get the first and second documents returned. I'm trying to get players from a certain team for that year and I'm not sure how to structure my find to get the results I'm looking for.

I tried using

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

but it doesn't return anything. Am I using the $elemMatch wrong?

1 Answer 1

1

The teams field is an object and not an array, which I believe is why $elemMatch isn't working, because it is an array operator.

If you want to use $elemMatch, you could try a query like this, which specifies teams.MIN, which is an array:

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

But because this is an example of an $elemMatch with a single query condition, it would be simpler to do it like this:

db.Players.find({ "teams.MIN" : 2021 });
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! This is exactly right. I'm learning mongodb so this is helpful

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.