Query Operators

Introduction to MongoDB in Python

Filip Schouwenaars

Machine Learning Researcher

The $in operator

from pymongo import MongoClient
client = MongoClient()
mov = client.film.movies
curs = mov.find({
  "release_year": { 
    "$in": [2008, 2009] 
  }
})

list(curs)
[
      ...
     {
          '_id': '6824bbd05644e53adbf2750f',
          'title': 'iron man',
          'genre': ['action', 'adventure', 'sci-fi'],
          'rating': 7.9,
          'release_year': 2008,
    },
    {
          '_id': '6824bbd05644e53adbf27525',
          'title': 'dragonball evolution',
          'genre': ['action', 'adventure', 'fantasy'],
          'rating': 2.6,
          'release_year': 2009
    }
]
Introduction to MongoDB in Python

The $in operator on arrays

mov.find_one({ 
  "genre": "adventure" 
})
{
    '_id': '6824bbd05644e53adbf27500',
     'title': 'interstellar',
     'genre': ['adventure', 'drama', 'sci-fi'],
     'rating': 8.6,
     'release_year': 2014,
     'won_oscar': True
}
mov.find_one({
  "genre": {
    "$in": ["thriller", "fantasy"]
  }
})
{
    '_id': '6824bbd05644e53adbf27501',
     'title': 'inception',
     'genre': ['action', 'sci-fi', 'thriller'],
     'rating': 8.8,
     'release_year': 2010,
     'won_oscar': True
}
Introduction to MongoDB in Python

The $exists operator

curs = mov.find({
  "won_oscar": {
    "$exists": True 
  }
})
list(curs)
[
    ...
    {
        '_id': '6824bbd05644e53adbf27515',    
        'title': '12 angry men',
        'genre': ['crime', 'drama'],
        'rating': 9,
        'release_year': 1957,
        'won_oscar': False
    },
    {
        '_id': '6824bbd05644e53adbf27516',
        'title': 'get out',
        'genre': ['horror', 'mystery', 'thriller'],
        'rating': 7.8,
        'release_year': 2017,
        'won_oscar': True
    },
     ...
]
Introduction to MongoDB in Python

Combining queries with $and

mov.find_one({
  "$and": [
    { "genre": "comedy" },
    { "release_year": 2023 }
  ]
})

# Equivalent! mov.find_one({ "genre": "comedy", "release_year": 2023, })
{
    '_id': '6824bbd05644e53adbf27508',
    'title': 'barbie'
    'genre': [
        'comedy',
        'fantasy',
        'adventure'
    ],
    'rating': 6.9,
    'release_year': 2023,
}

Introduction to MongoDB in Python

Combining queries with $or

curs = mov.find({
  "$or": [
    { "genre": "comedy" },
    { "release_year": 2023 }
  ]
})

list(curs)
[
    {
        '_id': '6824bbd05644e53adbf274ff',
        'title': 'superbad',
        'genre': ['comedy', 'teen'],
        'rating': 7.6,
         'release_year': 2007
    },
    ...
    {
        '_id': '6824bbd05644e53adbf2750c',
          'title': 'm3gan',
          'genre': ['horror', 'sci-fi', 'thriller'],
          'release_year': 2023,
          'rating': 6.4,
          'won_oscar': False
    }
    ...
]
Introduction to MongoDB in Python

Let's practice!

Introduction to MongoDB in Python

Preparing Video For Download...