elemMatch behavior

I would like to understand how $elemMatch is implemented (logically speaking) to explain the following simple test case ;

db.testElemMatch.insertMany([
   { tableau: [ "1", "2" ] },
]);
//The first 2 commands returns the same result (the expected document)
//so does that mean that elemMatch search for satisfying each crtiteria with a differnet array element?
//.. regardless of query order
db.testElemMatch.find( { tableau : {$elemMatch: {$eq:"1", $eq:"2"} } } )
db.testElemMatch.find( { tableau : {$elemMatch: {$eq:"2", $eq:"1"} } } )
//Why that command returns the expected document as well since the first criteria is NOT satisfy 
db.testElemMatch.find( { tableau : {$elemMatch: {$eq:"5", $eq:"2"} } } )
//Why the criteria order affect the result here? 
db.testElemMatch.find( { tableau : {$elemMatch: {$eq:"2", $eq:"5"} } } )

None of the queries are what you think they are.

The first query is really

{ tableau : {$elemMatch: {$eq:"2"} } }

The second is really

{ tableau : {$elemMatch: {$eq:"1"} } }

Third

{ tableau : {$elemMatch: {$eq:"2"} } }

And finally the forth

{ tableau : {$elemMatch: {$eq:"5"} } }

A query is a JSON document. In most implementation of JSON, only the last occurrence of key is significant. In this case the key is $eq. You have to use $and which takes an array.

You may find what you queries are in mongosh with

query = { tableau : {$elemMatch: {$eq:"2", $eq:"5"} } }

or by looking at the parsed query in the explain plan.

1 Like

Thank you so much, crystal clear

1 Like