Aan de slagGa gratis aan de slag

The $and operator

Sometimes, you need to find documents that meet multiple conditions at the same time. In MongoDB, this is where the $and operator comes in:

{ "$and": [{ "field1": value1, "field2": value2 }] }

But there's also a shortcut: If each condition applies to a different field, you can simply include multiple key-value pairs in your filter. MongoDB will implicitly apply an AND between them:

{ "field1": value1, "field2": value2 }

Tip: To refresh your memory on all available fields in the movies collection, you can run mov.find_one(); this will print out the first document in the collection.

Deze oefening maakt deel uit van de cursus

Introduction to MongoDB in Python

Cursus bekijken

Oefeninstructies

  • Find all movies that have a rating less than or equal to 6.5 but still managed to win an Oscar.
  • Turn the resulting cursor object into a list and store the result as low_oscar.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

# Movies with rating < 6.5 that won oscar
low_oscar_curs = mov.find({
  ____,
  ____
})

# Convert from cursor to list
low_oscar = ____

print(f"Found {len(low_oscar)} documents:")
print(low_oscar)
Code bewerken en uitvoeren