Sling Academy
Home/Python/PyMongo: Using $and, $or, $not, $nor operators (6 examples)

PyMongo: Using $and, $or, $not, $nor operators (6 examples)

Last updated: February 09, 2024

Introduction

This tutorial covers the usage of logical operators $and, $or, $not, and $nor in PyMongo, a popular Python distribution used for working with MongoDB. Applying these logical operators enhances query capabilities, allowing for more precise data retrieval. Throughout this guide, we’ll explore various scenarios showcasing each operator’s functionality, from basic to advanced examples. Prior understanding of MongoDB and basic Python is recommended for following along with the examples provided.

Setting Up Your Environment

Before diving into the examples, ensure PyMongo is installed in your environment:

pip install pymongo

Additionally, have a MongoDB instance running and accessible from your Python environment. This guide assumes you’re using a local MongoDB server.

Preparing the Data

For demonstration, let’s consider a simple document structure in a collection named ’employees’ that records employee information:

{
  "name": "John Doe",
  "age": 30,
  "department": "Marketing",
  "salary": 50000
}

This collection will serve as our dataset for the examples to follow.

Basic Usage of Logical Operators

First, let’s kick off with the most straightforward use cases of each operator:

$and Operator

The $and operator allows you to specify multiple conditions that must all be met for a document to be selected. For instance, to find employees in the Marketing department who are over 25 years old:

from pymongo import MongoClient

client = MongoClient('localhost', 27017)
db = client.your_database_name.employees

query = {
  "$and": [
    {"department": "Marketing"},
    {"age": {"$gt": 25}}
  ]
}

documents = db.find(query)

for doc in documents:
  print(doc)

Output:

{
  "name": "John Doe",
  "age": 30,
  "department": "Marketing",
  "salary": 50000
}

$or Operator

The $or operator allows for selection when any of the specified conditions are met. For instance, finding employees in either the Marketing or Sales department:

query = {
  "$or": [
    {"department": "Marketing"},
    {"department": "Sales"}
  ]
}

documents = db.find(query)

# Output processing omitted for brevity

$not Operator

The $not operator inverses the condition. To find employees not in the Marketing department:

query = {
  "department": {"$not": {"$eq": "Marketing"}}
}

documents = db.find(query)

# Output processing omitted for brevity

$nor Operator

Similar to $not, $nor takes an array of conditions and selects if none are true. For employees neither in the Marketing department nor over 40 years:

query = {
  "$nor": [
    {"department": "Marketing"},
    {"age": {"$gt": 40}}
  ]
}

documents = db.find(query)

# Output processing omitted for brevity

Advanced Examples

With a grasp on each operator’s basic usage, let’s explore more complex queries demonstrating their combined usage.

Combining $and with $or

Finding employees who are either in the Marketing department or have a salary greater than 60000, and must be under 35 years old:

query = {
  "$and": [
    {
      "$or": [
        {"department": "Marketing"},
        {"salary": {"$gt": 60000}}
      ]
    },
    {"age": {"$lt": 35}}
  ]
}

documents = db.find(query)

# Output processing omitted for brevity

Nesting $not within $and

To intricately exclude employees from a specific age group while ensuring they belong to a specific department:

query = {
  "$and": [
    {"department": "IT"},
    {"age": {"$not": {"$in": [25, 30]}}}
  ]
}

documents = db.find(query)

# Output processing omitted for brevity

Conclusion

The power of logical operators in MongoDB queries, accessible through PyMongo, significantly enhances data retrieval precision. Starting with basic examples and moving into more complex scenarios, this guide provides a solid foundation in utilizing $and, $or, $not, and $nor operators. Harnessing these operators can refine your queries to meet precise conditions, thus making your application more data-driven and responsive to specific needs.

Next Article: How to check your PyMongo version and upgrade it

Previous Article: PyMongo bson.errors.InvalidDocument: Cannot encode object

Series: Data Persistence in Python – Tutorials & Examples

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types