I have this document structure:
{
"name": "ab",
"grades": [
{
"grade": "A",
"score": 1
},
{
"grade": "A",
"score": 12
},
{
"grade": "A",
"score": 7
}
],
"borough": "Manhattan2"
}
Assignment is to write a query to find the restaurants that have all grades with a score greater than 5.
The solution to the problem is following:
db.restaurants.find({
"grades": {
"$not": {
"$elemMatch": {
"score": {
"$lte": 5
}
}
}
}
})
I have troubles understanding proposed solution.
So far I have only used $elemMatch to match at least one element of array or elements in array's inner objects (grades.score), but how the heck $not is "somehow making" $elemMatch to check for all grades.score in this object?
I do understand general idea, "don't look at score less the equal to 5, and what remains is what we need", but I cannot comprehend what does this code snippet returns:
"$not": {
"$elemMatch": {
"score": {
"$lte": 5
}
}
}
If was asked what does this query do before running & testing it, I would say that it find first score that is greater then 5 and takes that document, but that is wrong, and I cannot figure why. I see that order of fields and keywords plays some role but don't see the connection.
From the docs for
$elemMatch{ "$elemMatch": { "score": { "$lte": 5 } } }will match documents which have at least one array element withscore <= 5.$noton that will match documents which don't meet that criteriascore <= 5"score > 5"