15 49.0138 8.38624 1 0 4000 1 https://wiese.xyz 300 0
theme-sticky-logo-alt

How to save data in MongoDB with Python3

0 Comments

For showing this simple example of MongoDB and Python, I have choosen Python3 and MongoDB v3.6.3 and I will use the Pycharm from Jetbrain.

First you need to install the dependecies, I have installed pymongo v3.10.1

pip3 install pymongo

Note: if doing this in “cmd” on Windows and fails, try again with Administrator rights.

This is when I install it from command-line in Windows Terminal

For installing MongoDB on your system to to the link under here:

Windows:
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-windows/
Mac:
https://docs.mongodb.com/manual/tutorial/install-mongodb-on-os-x/
Linux:
https://docs.mongodb.com/manual/administration/install-on-linux/


When you have made sure you have installed Python3 and MongoDB, then here is a simple script there will save and find the data saved:

from pymongo import MongoClient

myclient = MongoClient("mongodb://localhost")
mydb = myclient["test_database"]
mycol = mydb["test_table"]

# Data you want to save to MongoDB as JSON format
data_to_save = {'name': 'Marc Wiese', 'Interest': ['A', 'B']}
print('Data to save: ')
print(data_to_save)
mycol.insert(data_to_save)

# retrieving the data back from MongoDB
print('Data from MongoDB: ')
lookup = mycol.find_one();
print(lookup)

Remember to solution is very simple, and i will always get the first save you make, because the retrieve code only get one row back.

find_one() – This code only finds one row and returns it, if you want all found rows, you can use find().

Let’s say you save many people in your and want to find a specific one based on name, then you can write following code it will find me.

find({'name': 'Marc Wiese'})

You can also search text for a specific name like this:

find({'name': { "$regex": 'marc', "$options": "i"}})

The options “i” is for case-insensitive, so you can write Marc/marc and find the same record.