liveBook · Manning

Collection

As explained in The Quick Python Book, Fourth Edition

A collection is a MongoDB container that groups documents within a database.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains selection, lazy creation, CRUD operations, generated identifiers, and dropping collections, but not indexing or schema design.
Examples
Uses a PyMongo `docs` collection containing Jane’s profile, then demonstrates querying, updating, replacing, deleting, and dropping it.
What it assumes
Assumes general programming knowledge and access to a MongoDB server or MongoDB Atlas instance.
What you can do after
Apply it via PyMongo to create, query, modify, replace, delete, and drop MongoDB collections and their documents.
How it connects
Connects collections with databases, documents, BSON, ObjectId identifiers, and CRUD operations.

Also explained in

Compare how 16 books explain collection →

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.