$elemmatch

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.

example.

customers>names > first

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

…………….>likes

createDate

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

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

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)

.and(“likes”)

.is(value);

criteria = Criteria

.where(“customers”).elemMatch(subCriteria)

.and(“createDate”)

.gte(startDate).lte(endDate);