<jupyter_start><jupyter_text>PyMongo- driver to access the MongoDB database Install PyMongo<jupyter_code># run this command in terminal
! pip install pymongo
## test pymongo
import pymongo<jupyter_output><empty_output><jupyter_text>CRUD Operations with PyMongo Create operations- Create or insert operations add new documents to a collection    - if the collection does not currently exists, insert opertions will create the collection<jupyter_code>myclient = pymongo.MongoClient("mongodb://localhost:27017/")
students = myclient["students"]
# check if database exists
print(myclient.list_database_names())
help(myclient)
# create a collection called AdvPy
# collection is not created until it gets content
advPy = students["AdvPy"]
# print list of all collections in students database
print(students.list_collection_names())<jupyter_output>['myCollection', 'AdvPy']<jupyter_text>Insert Document- insert_one() and insert_many()<jupyter_code>stu1 = {'fname': 'Alice', 'lname':'Wonderland', 'stuid': 70012312, "grade1": 100, "grade2": 95}
doc = advPy.insert_one(stu1)
doc
print(doc.inserted_id)
stuList = [{'fname': 'Bob', 'lname':'Wood', 'stuid': 700123, "grade1": 90, "grade2": 85},
          {'fname': 'Joe', 'lname':'Jones', 'stuid': 700111, "grade1": 99, "grade2": 90}]
advPy.insert_many(stuList)
stuList = [{'fname': 'Bob', 'lname':'Wood', '_id': 700123, "grade1": 90, "grade2": 85},
          {'fname': 'Joe', 'lname':'Jones', '_id': 700111, "grade1": 99, "grade2": 90}]
advPy.insert_many(stuList)<jupyter_output><empty_output><jupyter_text>Find- Read/select documents from collections- find(), find_one()<jupyter_code># select * in SQL
# find returns cursor/iterator; can be converted into list
print(list(advPy.find()))
# iterate over each record/doc in collection/table
for stu in advPy.find():
    print(type(stu), stu)
# find specific record
stu = advPy.find({'_id':700123})
print(stu[0])
# everything is dict in MongoDB
# and operator
query = {'fname':'Alice', 'lname':'Wonderland'}
for stu in advPy.find(query):
    print(stu)
query = {"$or" : [{'fname':'Alice'}, {'lname':'Wood'}]}
for stu in advPy.find(query):
    print(stu)<jupyter_output>{'_id': ObjectId('5dcc0c0abe86f7810ba13efc'), 'fname': 'Alice', 'lname': 'Wonderland', 'stuid': 70012312, 'grade1': 100, 'grade2': 95}
{'_id': ObjectId('5dcc0c10be86f7810ba13efd'), 'fname': 'Bob', 'lname': 'Wood', 'stuid': 700123, 'grade1': 90, 'grade2': 85}
{'_id': 700123, 'fname': 'Bob', 'lname': 'Wood', 'grade1': 90, 'grade2': 85}<jupyter_text>Limit- find().limit(N)- limits the top N documents<jupyter_code>for stu in advPy.find(query).limit(1):
    print(stu)<jupyter_output>{'_id': ObjectId('5dcc0c0abe86f7810ba13efc'), 'fname': 'Alice', 'lname': 'Wonderland', 'stuid': 70012312, 'grade1': 100, 'grade2': 95}<jupyter_text>Sort- find().sort('key', 1/-1)- by default sorts in ascending order if 2nd argument to sort is ignored- -1 sorts the document in descending order<jupyter_code>for stu in advPy.find(query).sort('stuid'):
    print(stu)
for stu in advPy.find(query).sort('lname', -1):
    print(stu)<jupyter_output>{'_id': ObjectId('5dcc0c10be86f7810ba13efd'), 'fname': 'Bob', 'lname': 'Wood', 'stuid': 700123, 'grade1': 90, 'grade2': 85}
{'_id': 700123, 'fname': 'Bob', 'lname': 'Wood', 'grade1': 90, 'grade2': 85}
{'_id': ObjectId('5dcc0c0abe86f7810ba13efc'), 'fname': 'Alice', 'lname': 'Wonderland', 'stuid': 70012312, 'grade1': 100, 'grade2': 95}<jupyter_text>Update- update existing records- update_one(), update_many()- if update_one() query finds more than one matching record, the first one will be updated<jupyter_code>query = {'_id': 700123}
newValues = { "$set": {'grade1': 95, 'grade2': 100}}
advPy.update_one(query, newValues)
print(advPy.find(query)[0])
x = advPy.update_many({'fname':'Alice'}, {'$set':{'lname': 'Wonderful'}})
print(x.modified_count, "documents updated!")
print(list(advPy.find({})))<jupyter_output>[{'_id': ObjectId('5dcb87c95161b837644bc9b0'), 'fname': 'John'}, {'_id': ObjectId('5dcb88b65161b837644bc9b1'), 'fname': 'Jake'}, {'_id': ObjectId('5dcb88b65161b837644bc9b2'), 'fname': 'Jen'}, {'_id': ObjectId('5dcb92f7be86f7810ba13ef6'), 'fname': 'Alice', 'lname': 'Wonderful', 'stuid': 70012312, 'grade1': 100, 'grade2': 95}, {'_id': ObjectId('5dcb939fbe86f7810ba13ef7'), 'fname': 'Alice', 'lname': 'Wonderful', 'stuid': 70012312, 'grade1': 100, 'grade2': 95}, {'_id': ObjectId('5dcb93a7be86f7810ba13ef8'), 'fname': 'Alice', 'lname': 'Wonderful', 'stuid': 70012312, 'grade1': 100, 'grade2': 95}, {'_id': ObjectId('5dcb94e9be86f7810ba13ef9'), 'fname': 'Bob', 'lname': 'Wood', 'stuid': 700123, 'grade1': 90, 'grade2': 85}, {'_id': ObjectId('5dcb94e9be86f7810ba13efa'), 'fname': 'Joe', 'lname': 'Jones', 'stuid': 700111, 'grade1': 99, 'grade2': 90}, {'_id': 700123, 'fname': 'Bob', 'lname': 'Wood', 'grade1': 95, 'grade2': 100}, {'_id': 700111, 'fname': 'Joe', 'lname': 'Jones', 'grade1': 99, 'grade2':[...]<jupyter_text>Delete - delete_one() or delete_many() methods let you delete documents<jupyter_code>x = advPy.delete_one({'fname':'Alice'})
print(x.deleted_count, 'documents deleted.')
x = advPy.delete_many({'fname:':'Alice'})
print(x.deleted_count, 'documents deleted.')
print(list(advPy.find({})))
# delete all the records from advPy collection
x = advPy.delete_many({})
print(x.deleted_count, 'documents deleted.')<jupyter_output>8 documents deleted.
{'fraction_non_alphanumeric': 0.1961150541651102, 'fraction_numerical': 0.08442286141202839, 'mean_word_length': 7.568, 'pattern_counts': {'":': 11, '<': 27, '<?xml version=': 0, '>': 27, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '437180', 'license': 'MIT', 'n_tokens_mistral': 2359, 'n_tokens_neox': 2033, 'n_words': 480, 'path': 'PyMongo.ipynb', 'repo_name': 'rambasnet/MongoPython', 'size': '5354'}