Filter syntax with two elements?

Hi,
I tried to filter movieDetails database from M001 course. Filter for 2 actors returns more result than filtering on 1 author. Is it correct???

MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movieDetails.find({“actors”:“Kevin Kline”}).count()
5
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movieDetails.find({“actors”:“Kevin Kline”,“actors”:“Will Smith”}).count()
6
MongoDB Enterprise Cluster0-shard-0:PRIMARY> db.movieDetails.find({“actors”:“Kevin Kline”,“actors”:“xxx”}).count()
0

Hi,

  1. first command is true, as you filtered for actor “kevin kline” and results to output 5.
  2. You should not use same column twice in the filter statement (it not true actually it acts as $in operator).
  3. use the below command to fitler the collection for more than one elements:
    db.movieDetails.find( {actors: [ “Kevin Kline”, “Will Smith” ] } )

Note: This actually filnd the documents in exactly the order we pass in the filter.

  1. use $all command to ignore the order and search for the filter:
    db.movieDetails.find( { tags: { $all: [ “Kevin Kline”, “Will Smith” ] } } )

Check this and kindly update if there is any issues or concerns.

1 Like

Thanks,

I don’t fully understand the syntax when I use one column twice. But I understand that to use AND and OR I need to specify the column once and use a proper operator:

  • { “actors”: { $all: [ “Kevin Kline”, “Will Smith” ] } —> both actors play together

  • {“actors”:{$in:[“Kevin Kline”,“Will Smith”]}} —> at least one plays

Correct?
PS
Super fast answer!

Yes, we should follow some rules, that’s why we get improper results if we use same column names in filter condition. that’s why all the special operators in places (as you updated) for multiple element filter for a particular field.

1 Like