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/")
['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.

To update

myquery = { "username": "Lee" }
newvalues = { "$set": { "date_joined": "2024-01-03 16:23:49" } }
mydb.mycol.update_one(myquery, newvalues)
query = > 5).order_by(id)
for pet in query:
    myquery = { 'cid': }
    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 = == pet).order_by(id)
for dog in query:
    myquery = { 'userid': pet }
    newvalues = {"$push": {'question': {'logid':int(,'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" }

To query

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

If you have an `and' query

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

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):

To query with regex

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

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 = == 6).count()

Another way is to use the count_documents method.

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

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