6

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?

user149402
  • 61
  • 3
  • 1
    Can you include the actual document you're passing into the query or the (looks like) Java code you're using to construct the query? Seems like they should both work. – Mason Aug 20 '13 at 13:02

1 Answers1

3

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

Chris Winslett
  • 826
  • 5
  • 6