Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot notation vs. $elemMatch

Tags:

mongodb

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?

like image 425
user149402 Avatar asked Aug 20 '13 12:08

user149402


1 Answers

$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.

like image 117
Chris Winslett Avatar answered Nov 15 '22 05:11

Chris Winslett