liveBook · Manning

Pymongo

As explained in The Quick Python Book, Fourth Edition

PyMongo is the official Python driver for connecting to and operating on MongoDB databases.

PyMongo connects Python programs to MongoDB servers through MongoClient. MongoDB organizes data into databases, collections, and documents; missing databases and collections appear when data is inserted. section 23.7

Core operations include:

  • Select a database and collection with client.my_data and db.docs. section 23.7
  • Insert Python dictionaries as documents; MongoDB adds a unique ObjectId. section 23.7
  • Retrieve the first document or match a specification with find_one(). section 23.7
  • Use update_one() with $set for field changes, replace_one() for whole-document replacement, and delete_one() for removal. section 23.7

Connect and insert a document

Install with pip, create MongoClient from the supplied connection string, select my_data.docs, and insert a dictionary containing fields such as name, age, interests, and date_added. section 23.7

import datetime
a_document = {'name': 'Jane',
              'age': 34,
              'interests': ['Python', 'databases', 'statistics'],
              'date_added': datetime.datetime.now()
}
db = client.my_data                                         #1
collection = db.docs                                        #2
result = collection.find_one()                              #3
db.list_collection_names()
[]
#1 Selects a database (which hasn’t been created yet)
#2 Selects a collection in the database (also not yet created)
#3 Searches for first item; no exception even if neither collection nor database exists yet

Shows database and collection selection, an initial empty lookup, and a sample Python document. section 23.7

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Demonstrates installation, connection, selection, insertion, retrieval, updating, replacement, deletion, and collection dropping without covering advanced queries.
Examples
Uses a Jane document, find_one lookups, an Ann update, a Maria replacement, deletion, and collection listing.
What it assumes
Assumes general Python knowledge and requires an available MongoDB server, connection details, and an installed PyMongo package.
What you can do after
Operate/configure a MongoDB connection and create, read, update, replace, delete, and drop document collections.
How it connects
Ties Python dictionaries and ObjectId values to MongoDB databases, collections, documents, and CRUD operations.

Also explained in

Compare how 2 books explain pymongo →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.