user149402
user149402

Reputation: 81

Dot notation vs. $elemMatch

I have a unitScores collection, where each document has an id and an array of documents like this:

"_id": ObjectId("52134edd5b1c2bb503000001"),
"scores": [
  {
      "userId": ObjectId("5212bf3869bf351223000002"),
      "unitId": ObjectId("521160695483658217000001"),
      "score": 33
  },
  {
      "unitId": ObjectId("521160695483658217000001"),
      "userId": ObjectId("5200f6e4006292d308000008"),
      "score": 17
  }
]

I have two find queries:

_id:new ObjectID(scoreId)
"scores.userId":new ObjectID(userId)
"scores.unitId":new ObjectID(unitId)

and

_id:new ObjectID(scoreId)
scores:
  $elemMatch:
    userId:new ObjectID(userId)
    unitId:new ObjectID(unitId)

I would expect them to give the same result, but using the input userId and unitId of

userId: 5212bf3869bf351223000002
unitId: 521160695483658217000001

the dot notation version returns the wrong array entry (the one with score:17) and the $elemMatch returns the correct entry (the one with score:33). Why is that?

Upvotes: 8

Views: 1665

Answers (1)

Chris Winslett
Chris Winslett

Reputation: 836

$elemMatch is not the same logic as dot notation. $elemMatch requires the same nested elements to have the values. Using dot notation allows for any nested elements to have an values. Thus, your seeing different results because the query logic is different.

Upvotes: 3

Related Questions