PyMongo = MongoDB Python

Posted under » Python » MongoDB on 7 Jan 2024

It's great if you can combine the data of MySQL and MongoDB together. I prefer doing this using Python via Jupyter Notebook.

PyMongo has its limitation but you can use mongosh at the same time to overcome the limitation. It is also important that you don't mix up these two.

First you need to install pymongo. For starters let's see what have we got.

import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
print(myclient.list_database_names())
['admin', 'school', 'config', 'local']

Note that PyMongo is pythonic and doesn't sound like mongosh commands where the equivalent of `list_database_names' is `show dbs'.

Create a collection called "students"

myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["school"]
mycol = mydb["students"]

In MongoDB, we will mostly work with collections. So mycol will be used more often. mycol is short for db.students that we use in mongosh.

Insert in a key/value format or dictionary format.

mydict = { "name": "hanafi"}
x = mycol.insert_one(mydict)

Note that it is similiar to the `insertOne' command. If you wish to iterate

for cat in query:
        mydict = { "cid": int(pet), "username" : str(cat.username)}
        x = psy.insert_one(mydict)

To update

myquery = { "username": "Lee" }
newvalues = { "$set": { "date_joined": "2024-01-03 16:23:49" } }
mydb.mycol.update_one(myquery, newvalues)
or
query = quiz_question.select().where(quiz_question.test_id > 5).order_by(id)
for pet in query:
    myquery = { 'cid': pet.id }
    newvalues = { "$set": { 'text': pet.text } }
    mydb.mth.update_one(myquery, newvalues)

It is smart enough to add the colon when it is text and omit when it is numbers. You can put the int() like below to be safe.

If you need to do object embeddings, you don't have to put []. It will insert for you

query = quiz_question_log.select().where(quiz_question_log.user_id == pet).order_by(id)
for dog in query:
    myquery = { 'userid': pet }
    newvalues = {"$push": {'question': {'logid':int(dog.id),'qid':int(dog.question_id),},} }
    mydb.mthstuque.update_one(myquery, newvalues)

To view

for x in mycol.find():
  print(x) // one line
pprint.pprint(mycol.find_one()) // with return

To delete

myquery =  { "username": "Lee" }
mycol.delete_one(myquery) 

To query

myquery =  { "username": "Lee" }
for x in mycol.find(myquery):
  print(x)

If you have an `and' query

myquery =  { "username": "Lee", 'psy108b' : 1  }
for x in mycol.find(myquery):
  print(x)

As mentioned earlier, collections are stored in Python dictionary format. To show the value of a key

myquery =  { "username": "Lee" }
for x in mycol.find(myquery):
  print(x["first_name"])

To query with regex

myquery = { "address": { "$regex": "^S" } }
mydoc = mycol.find(myquery)
for x in mydoc:
  print(x) 

Note that you have to put "$regex" instead of just $regex

To truncate

x = mycol.delete_many({})
print(x.deleted_count, " documents deleted.") 

To count, which is Pythonic and similar to Django API.

query = quiz_question_log.select().where(quiz_question_log.test_id == 6).count()
print(query)

Another way is to use the count_documents method.

mycol.count_documents({'psy107b' : 1 })

For embedded objects.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS data