MongoDB - python

Project Description

Build a MongoDB database of people and phone numbers using Python3 and the PyMongo module. The tasks are described HERE .

Note: ask the instructor about the user_interface.py (link) module.

After every thing is working, create a GUI (Graphical User Interface)?

Test data

First NameLast NameNicknamePhone Number
TommyRot666-555-8888
JudyZedZ626-555-9999
PiccoloPete626-555-1234
ArleenPeteButtercup

Code examples/snippets

MongoDB Python Client

#! /usr/bin/python3

from pymongo import MongoClient

client = MongoClient()

####client = MongoClient('mongodb://localhost:27017')

print(client)

Create database

Note: In MongoDB, a database is not created until it gets content.

#! /usr/bin/python3

from pymongo import MongoClient

database = 'phonedb'

print('create database {database}')

client = MongoClient()

phonedb = client[database]

dbs = client.list_database_names()
for d in dbs:
    print(f'database: {d}')

create a collection in the database

#! /usr/bin/python3

from pymongo import MongoClient

database   = 'phonedb'
collection = 'phones'

print('create a collection')

client = MongoClient()

db = client[database]

col = db[collection]

dbs = client.list_database_names()
for d in dbs:
    print(f'database: {d}')

cols = db.list_collection_names()
print(f'{len(cols)} collections found')
for coll in cols:
    print(f'collection: {c}')

Insert document into a collection

#! /usr/bin/python3

from pymongo import MongoClient
import pprint

pp = pprint.PrettyPrinter()

database   = 'phonedb'
collection = 'phones'

doc = { 'firstname': 'Tom', 'lastname': 'Rot',
        'phonenumber': '666-555-8888' }

print(f'insert into collection {collection}')

client = MongoClient()
db     = client[database]
col    = db[collection]

results = col.insert_one(doc)
print(f'insert results: {results}')

dbs = client.list_database_names()
for d in dbs:
    print(f'database: {d}')

cols = db.list_collection_names()
print(f'{len(cols)} collections found')
for c in cols:
    print(f'collection: {c}')

x = col.find_one()
pp.pprint(x)

Drop database

#! /usr/bin/python3

from pymongo import MongoClient

database = 'phonedb'

print(f'drop database {database}')

client = MongoClient()

results = client.drop_database(database)

print(f'drop results: {results}')

dbs = client.list_database_names()
for d in dbs:
    print(f'database: {d}')