MongoDB and Python

In this post, i will provide the minimal requirement to work with Python and apply CRUD operations.

Fist of all you will need Python V.3 and the module pymongo.

After installing python 3. Please read this article to see how to install pymongo ==> https://www.mongodb.com/docs/drivers/pymongo/

You will also see the compatibility matrix of pymongo driver and mongodb versions on the link above.

Now that you installed pymongo, we are ready to start.

I suggest you to install Visual Studio Code ==> https://code.visualstudio.com/download

My git repository is available here ==> https://github.com/djmhd/PythonMongoDB

Clone the repo and update the property file “config.properties” if needed to put the correct mongodb:

git clone https://github.com/djmhd/PythonMongoDB.git
  • Hostname port
  • Credentials: user password
  • Query parameter connection string
  • Database name

Run the file testCRUD.py

python3 testCRUD.py

This will, create a collection sampleCollection.

It will add two documents.

{
_id:6298b571f5643949130bda03
firstName: "John"
lastName: "Doe"
Address: "First addresss"
}
and
{
_id:6298b571f5643949130bda55
firstName: "Brandon"
lastName: "Don"
Address: "Secondaddresss"
}

The unit test file will wait for any key on the prompt command line.

You can go check that the two document are well inserted.

After it will delete the second document.

The unit test file will wait for any key on the prompt command line.

You can go check that the second document is well removed.

Then it will update the first document to update the field from the value to …..

{
_id:6298b571f5643949130bda03
firstName: "Marc"
lastName: "Doe"
Address: "First addresss"
}