Not getting 23 results for lecture lab $match

I am using $match with aggregation method but not getting correct results. I am getting 26 results if I use $nin in genres field and 32 if I use $ne. I have spent lot of time to fix this but not able to do.
I think I am not able to understand the question a bit

  • imdb.rating is correct. i.e less than or equal to 7
  • genres -> It should not contain both “Crime” or “Horror” or we can have either one of them. As I understood either “Crime” should be their or “Horror”. We can not have both of them in genres field
  • rated is correct -> Its either “PG” or “G”
  • languages -> Its also correct, it contains “English” and “Japanese”

The genres part is the most likely culprit. Write some pipelines and experiment with the $nin or $ne operators when working with array fields. Also explore others like $setIntersection. And be aware that

[ C , H ] is $ne [ H , C ]

I used both $nin and $ne for genres. If I use $nin then it gives 26 results and if I use $ne then it gives 32 results.

I already saw from your first post that you tried with $nin and $ne. As you saw by yourself they are not the solution. Have you try with other operators? Have you look at $setIntersection?

Hi @Bhartendush,

We can debug your aggregation pipeline in the inbox message.
Please check your discourse inbox and let me know if you have any questions.


I don’t get 23 neither. I got 24. Can someone confirm 23 is correct?

Also I think the 2nd condition should be phased below:

  • genres does not contain “Crime” NOR “Horror”

23 is correct.

Thanks! May I send you query statement and so you can take a look?

Most people struggle with the languages field.

I am fine with the languages (array). Just include both English and Japanese using {‘languages’: {$elemMatch: { $eq: “English” }}}, {‘languages’: {$elemMatch: { $eq: “Japanese”}}}

That should work. Take a look at

Other frequent errors are with misspelled fields or values.

My issue is $elemMatch doesn’t work as expected for 573a13e7f29313caabdc8bb0. In the following query, no record should be returned, but $elemMatch + $ne does not filter out the document. Can you tell me why?

db.movies.aggregate([ { $match:{ $and: [{ ‘_id’: ObjectId(“573a13e7f29313caabdc8bb0”)}, {‘genres’: {$elemMatch: {$ne: “Drama”}}}]}}, {$project: {genres: 1}}])

If the array has an element that is not equal to the value then the whole expression is true.

Assume array = [ 4 , 5 ] and { elemMatch : { $ne : 4 } }. The value 5 is not equal to 4, so the expression is { $ne : 4 } is true. So elemMatch is true.

I think you might be interested with

1 Like

Got it. It makes total sense to me. Thanks!