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?
$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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With