liveBook · Manning

Pymongo

As explained in MongoDB 8.0 in Action, Third Edition

PyMongo is the official Python driver for connecting applications to MongoDB and performing database operations.

PyMongo is the official Python driver for connecting applications to MongoDB and performing database operations. It is the preferred choice for synchronous Python applications, where database calls proceed in a straightforward, sequential flow. section 3.6 section 3.6.3

A typical PyMongo workflow is:

  • Install the driver with pip. section 3.6.1
  • Create a MongoClient with a connection string and, when supported, specify Stable API version 1. section 3.6.1
  • Select a database and collection, define a query, and execute operations such as find_one. section 3.6.1
  • Handle exceptions, inspect returned documents, and close the connection. section 3.6.1

Find a route from JFK

Connect with MongoClient, select the sample_training database and routes collection, then run {"src_airport": "JFK", "airline.id": 3201}. A matching document contains airline, destination, codeshare, stops, and airplane fields. Run the saved script with python3 mongodb-pymongo.py. section 3.6.1

python3 -m pip install pymongo

Install PyMongo before importing MongoClient or using the driver. section 3.6.1

from pymongo import MongoClient

def vector_search():
    # MongoDB connection string
    uri = 'your_mongodb_connection_string'
    # Create a new MongoClient
    client = MongoClient(uri)

    try:
        # Connect to the MongoDB server
        client = MongoClient(uri)
        # Select the database and collection
        database = client['your_database_name']
        collection = database['your_collection_name']

        # Define the pre-filters and vector search query
        query = {
            "$and": [
                {"category": "electronics"},  # Example pre-filter
                {"price": {"$lt": 500}},  # Another example pre-filter
                {
                    "$vectorSearch": {
                        "queryVector": [/* your query vector here */],
                        "numResults": 10,
                        "path": "your_vector_field_name"
                    }
                }
            ]
        }

        try:
            # Execute the vector search query
            ➥ # and convert the results to a list
            results = list(collection.find(query))
            # Print the results
            for result in results:
                print(result)
        except Exception as query_error:
            # Handle errors that occur during the query execution
            print('Error executing vector search query:', query_error)
    except Exception as connection_error:
        # Handle errors that occur while connecting to MongoDB
        print('Error connecting to MongoDB:', connection_error)
    finally:
        try:
            # Ensure the MongoDB client is closed
            client.close()
        except Exception as close_error:
            # Handle errors that occur while closing the MongoDB connection
            print('Error closing MongoDB connection:', close_error)

# Call the vector_search function
vector_search()

Use the Python client to combine category and price prefilters with $vectorSearch, then collect and print similarity results. section 12.4.2

How MongoDB 8.0 in Action, Third Edition covers it

How deep it goes
Walks through installation, connection, database selection, querying, error handling, and closure, while deferring asynchronous execution to Motor.
Examples
Demonstrates a JFK route lookup and a category- and price-prefiltered vector search.
What it assumes
Assumes basic Python and MongoDB connection knowledge while showing installation and Atlas connection-string usage.
What you can do after
Build it from scratch to install PyMongo, connect to MongoDB, run queries, and perform filtered vector searches.
How it connects
Ties PyMongo to MongoDB, BSON, GridFS, Stable API, aggregation, Motor, and vector search.

Also explained in

Compare how 2 books explain pymongo →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of MongoDB 8.0 in Action, Third Edition. The section links point to the parts of the book it draws on.