MongoDB – Queries with Python
This is an article for people who have already installed MongoDB on their pc and want to do more with a Python script and the database.
Installed version of MongoDB
- MongoDB: 7.0.25
 - MongoShell: 2.5.9
 
What is Pymongo?
Pymongo is like a toolbox that allows your Python programme to communicate with the MongoDB database. Think of it this way: MongoDB is the large chest of drawers containing your data, and Pymongo is the set of tools your Python programme needs to open drawers, insert new notes (documents), search for specific notes, or modify notes.
With Pymongo, your Python code can send commands to MongoDB to store and retrieve data. It helps Python understand the ‘language’ of MongoDB so that the two can work well together. In short, Pymongo connects your Python programme to your MongoDB database.
Installation of Pymongo
Go to the terminal in Windows / Mac / Linux and type the command pip install pymongo. Then the package will be installed.
What is regex?
Think of ‘regex’ as a very clever placeholder or search pattern that you can use to search your data. Instead of searching for a specific word, you can use ‘regex’ to search for words that have a certain pattern.
For example, you could use regex to find all words that start with ‘apple’ or all numbers that start with ‘19’. It’s like a super filter that helps you find exactly the information you need, even if you don’t know exactly how it’s spelled.
Installation of regex
Regex is a query, a built-in command in the MongoDB database.
The script
import pymongo
a = pymongo.MongoClient("mongodb://localhost:27017/")
b = a["Laender"]
mycol = b["Espana"]
myquery = {"Ciudad": {"$regex": "^Santa"}}
mydoc = mycol.find(myquery)
for x in mydoc:
	print(x)
The command
regex = search for all ciudads (town) that begins with Santa
The output
{‚_id‘: ObjectId(‚634bbdd61b2e4576464e7285‘), ‚Com autónoma‘: ‚Canarias‘, ‚Provincia‘: ‚Santa Cruz de Tenerife‘, ‚Ciudad‘: ‚Santa Úrsula‚, ‚Isla‘: ‚Tenerife‘, ‚Altitud‘: 284, ‚Superficie‘: 22.59, ‚Núcleos de poplación‘: 9, ‚Poplación‘: 15114, ‚Densidad‘: 669.06, ‚Código postal‘: 38390, ‚Playa‘: ‚No‘, ‚Ayuntamiento‘: ‚Carr. España, 2, 38390 Sta Úrsula, Santa Cruz de Tenerife, España‘, ‚Ayuntamiento internet‘: ‚http://www.santaursula.es/‘, ‚Alojamiento‘: ‚CORAL LA QUINTA PARK SUITES Coral Villas La Quinta Vistamar ‚, ‚Autopista‘: ‚TF-5‘, ‚CN‘: ‚TF-217‘, ‚Lineas‘: ‚El Calvario Santa Ursula (T)‘, ‚Biblioteca‘: ‚C. Alcalde Alejo Perez, 1, 38390 Sta Úrsula, Santa Cruz de Tenerife, España‘, ‚Iglesia‘: ‚Parroquia Santa Úrsula C. Alcalde Fernando Luis, 3, 38390 Sta Úrsula, Santa Cruz de Tenerife, España http://www.parroquiasantaursula.com/‘, ‚Otros‘: ‚Fabulosa Tenerife : Perfumes árabes, trajes novias y novio David Rodríguez Café – Pastelería Arqing Servicios de Arquitectura e Ingeniería Bodega El Zacatín ‚}