A collection is a MongoDB container that groups BSON documents within a database. Unlike relational tables, it stores document-shaped key-value data and can accommodate unstable schemas. section 23.7
With PyMongo, select a database and collection through attributes. MongoDB can defer creating both until the first document is inserted; an empty collection can be queried without raising an exception. section 23.7
Typical collection operations include:
- Insert a document, which receives a unique ObjectId when no identifier is supplied. section 23.7
- Retrieve the first document or match one by a specification such as its ObjectId. section 23.7
- Update selected fields with $set, replace an entire document, delete matching documents, or drop the collection. 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
Follow the compact PyMongo sequence from selecting a database and collection through querying an initially empty store. section 23.7
A small document lifecycle
A `docs` collection can store Jane’s name, age, interests, and timestamp; update her name to Ann, replace the document with `{name: "Maria"}`, then delete it. Listing collection names shows creation after insertion and an empty database after dropping it. section 23.7















