Match Array Value Elements with $elemMatch - MongoDB

I don’t get a lot of time to share these days, but when something really frustrates the crap out of me and then you finally get the understanding and code working, it’s something that needs to be shared.


customers>names > first

 ………………………..> last



when trying to validate arrays in mongo db, you can run into matching issues when arrays have multiple indexes but with matching array values in separate nodes.

  ie..   frank likes hockey and peter likes soccer.

if your criteria


matches this is why.

$elemMatch  will allow you to match the entire element in the array.

{“customers” : {“$elemMatch” : {names.first:“frank”,likes:“soccer”}}}

will not match.. which is the expected result.

Spring Data MongoDB elemMatch example:

 Criteria subCriteria = Criteria.where(“name.first”).is(name)



criteria = Criteria