# pymongo allows python to speak with mongoDB
import pymongo
# connect to mongoDB server, db and collection
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["user_database"]
mycol = mydb["users"]
# remove all documents - here for testing
mycol.drop()
print("dropped all documents from users collection")
dropped all documents from users collection
# insert a user and print inserted id
data1 = {'username': 'joe', 'password': 'schmoe'}
x = mycol.insert_one(data1)
print("inserted",x.inserted_id)
# insert another user
data2 = {'username': 'lou', 'password': 'blue'}
x = mycol.insert_one(data2)
inserted 679ff4ff398cb33175c1740e
# get one record
one = mycol.find_one({'username':'lou'})
print(one)
{'_id': ObjectId('679ff4ff398cb33175c1740f'), 'username': 'lou', 'password': 'blue'}
_id = one.get('_id')
result = mycol.delete_one({'_id':_id})
print(result)
DeleteResult({'n': 1, 'ok': 1.0}, acknowledged=True)
# get all records
all = mycol.find()
all_list = list(all)
print("all records:",all_list)
all records: [{'_id': ObjectId('679ff4ff398cb33175c1740e'), 'username': 'joe', 'password': 'schmoe'}]
# use a python list to add many documents
myrecords = [{ "name": "John", "role": "customer" },
{ "name": "Jane", "role": "customer" },
{ "name": "Joe", "role": "employee" },
{ "name": "Julie", "role": "employee" }]
x = mycol.insert_many(myrecords)
#print("inserted", x.inserted_ids)
# use a python dict to specify query parameters
myquery = {'role':'customer'}
result = mycol.find(myquery)
result_list = list(result)
print("results:",result_list)
results: [{'_id': ObjectId('679ff4ff398cb33175c17410'), 'name': 'John', 'role': 'customer'}, {'_id': ObjectId('679ff4ff398cb33175c17411'), 'name': 'Jane', 'role': 'customer'}]
# use a python dict to specify query parameters
myquery = {'role':'customer'}
myquery_new = {'role' : 'consumer'}
mycol.update_many(myquery, {'$set': myquery_new})
result = mycol.find(myquery_new)
result_list = list(result)
print("results:",result_list)
results: [{'_id': ObjectId('679ff4ff398cb33175c17410'), 'name': 'John', 'role': 'consumer'}, {'_id': ObjectId('679ff4ff398cb33175c17411'), 'name': 'Jane', 'role': 'consumer'}]
# delete all documents with role==consumer
myquery_new = {'role' : 'consumer'}
mycol.delete_many(myquery_new)
# get all
r = list(mycol.find())
print(r)
[{'_id': ObjectId('679ff4ff398cb33175c1740e'), 'username': 'joe', 'password': 'schmoe'}, {'_id': ObjectId('679ff4ff398cb33175c17412'), 'name': 'Joe', 'role': 'employee'}, {'_id': ObjectId('679ff4ff398cb33175c17413'), 'name': 'Julie', 'role': 'employee'}]