Ungraded Quiz - Syntax problem in solution

Hi all,

Although I solved the final ungraded quiz, I have a question. I recall shannon said that a simple filter matching two or more criteria is essentially the same like building a query with the $and operator.

So this

db.movieDetails.find(
{
    $and : [
        {
            "tomato.meter" : {
                $gt : 95
            }
        }, {
            "metacritic" : {
                $gt : 88
            }
        }
    ]
}, {
    _id : 0, title: 1, "tomato.meter":1, metacritic:1
}

);

is actually the same like this

db.movieDetails.find(
{
“tomato.meter” : {
$gt : 95
}
}, {
“metacritic” : {
$gt : 88
}
}, {
_id : 0, title: 1, “tomato.meter”:1, metacritic:1
}
);

So why does this

{results : {$elemMatch: {$gte :70, $lt: 80}}}

work but this

{results : {$elemMatch : {$and : [{$gte :70}, {$lt: 80}]}}}

does not?

Thanks for explanation in advance! Have a nice day!
Btw, great course!
Cheers

Marco

@Marco_80669

From the docs

$gt selects those documents where the value of the field is greater than (i.e. > ) the specified value .

Meaning that the { $gte:70 } and { $lt:80 } need to have a field associated with them. Like { someField: { $gte: 70 } } Or from your example

{ 
  tomato.meter: { $gt: 95 }
}

Also you are comparing the ‘anding’ which $elemMatch is doing to the $and query operator which are not the same.

The $elemMatch operator matches documents that contain an array field with at least one element that matches all the specified query criteria.

However the $and query operator and a filter used with db.collection.find() with 2 or more conditions are the same! :+1: See this doc for what the video is referring to.

Also welcome and best of luck with the rest of the class! :slightly_smiling_face:

1 Like

Hi @Marco_80669,

You can also refer to the following post to understand difference between the usage of $and operator and $elemMatch operator:

Please let me know, if you have any questions.

Thanks,
Sonali