Basic CRUD Operations (via pymongo)


In [ ]:
# import pymongo
from pymongo import MongoClient

In [ ]:
# Create client
client = MongoClient('mongodb://localhost:32768')

In [ ]:
# Connect to database
db = client['mongo_meetup']

In [ ]:
# Get collection
my_collection = db['users']

Helper Functions


In [ ]:
def print_users(users):
    """Print 0-N mongo documents"""
    for idx, user in enumerate(users):
        print(f'{idx}: {user}')

In [ ]:
def print_all_users(my_collection):
    """Print all the users in the 'users' collection"""
    users = my_collection.find({})
    print('--- All Users ---')
    print_users(users)

CREATE

"INSERT" in SQL


In [ ]:
# Note syntax change: All keys now wrapped in quotes (name goes to python "name")

doc = {
    "name": "Sue",             # "field": value
    "email": "sue@gmail.com",  # "field": value
    "age": 26,                 # "field": value
    "status": "pending"        # "field": value
}

result = my_collection.insert_one(doc)

print(f'result: {result}')

In [ ]:
# Insert a second user
doc = {
    "name": "Johnny",
    "email": "johnny@gmail.com",    
    "age": 13,
    "status": "pending"
}
user_2_id = my_collection.insert_one(doc).inserted_id
print(f'user_2_id: {user_2_id}')

In [ ]:
print_all_users(my_collection)

READ

("SELECT" in SQL)


In [ ]:
# Note syntax change: "true" goes to python "True" (Can use 1 instead of true/True)
# Note syntax change: "$gte" wrapped in quotes

users = my_collection.find(
    { "age": { "$gte": 18 } },                        # query criteria
    { "_id":False, "name": True, "address": True }    # projection
).limit(5)                                            # cursor modifier

In [ ]:
print(f'Type: {type(users)}')

In [ ]:
print_users(users)

UPDATE

("UPDATE" in SQL)


In [ ]:
# Note syntax change: method "updateMany" renamed to "update_many" (more pythonic)

my_collection.update_many(
    { "age": { "$lt": 18 } },
    { "$set": { "status": "reject" } }    
)

DELETE

("DELETE" in SQL)


In [ ]:
# Note syntax change: method "deleteMany" renamed to "delete_many" (more pythonic)

db.users.delete_many(
    { "status": "reject" }
)

In [ ]:
print_all_users(my_collection)

DELETE/DROP 'Users'


In [ ]:
# DANGER!!! ("DELETE FROM users" in SQL)
db.users.delete_many({});

# DANGER!!! ("DROP TABLE users" in SQL)
db.users.drop();