I'm going through the PyMongo tutorial and there's one thing that I don't understand.
We are shown that we can create a database collection like this:
>>>client = MongoClient()
>>>print(client)
MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True)
>>>db = client.test_database
>>>print(db)
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database')
>>>collection = db.test_collection #posts is the collection.
>>>print(collection)
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'test_database'), 'test_collection')
My initial thought was: "Did they make sure to include a test_database
attribute for the client and a test_collection
attribute for the database just to make it work with the tutorial?" But further experimentation showed me that I could create databases and collections in this way with any "attribute name" I please! For example:
>>>client = MongoClient()
>>>db = client.foo
>>>print(db)
Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'foo')
>>>collection = db.bar
>>>print(collection)
Collection(Database(MongoClient(host=['localhost:27017'], document_class=dict, tz_aware=False, connect=True), 'foo'), 'bar')
How does this work in Python? I've tried to understand it by reading the pymongo files in the GitHub repository but it's quite difficult for a newbie to understand.