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

