PYTHON AND MONGODB
Let’s start talking about “Python and MongoDB“. The traditional model for representing data in a database is the relational model. In this article we will take as an example a new data representation model that does not use the relational model and the SQL language to query it but a totally different approach based on MongoDB.
JSON
JSON (Javascript Object Notation) is a lightweight data representation and interchange format. It is based on a subset of the javascript programming language. JSON is built starting from two basic structures, practically present in all programming languages, namely objects and arrays. Objects are collections and associations between names and values, more precisely keys and values as happens in Python with dictionaries. Arrays are instead ordered lists of values, just think of lists in Python.
PYTHON AND MONGODB – REPRESENTATION OF A JSON OBJECT
The representation of a JSON object begins with an opening brace and ends with a closing brace. The key or name always consists of a string separated from the value with a colon. If there are more elements, each key-value pair must be separated with a comma. The values are also those present in javascript and are highlighted in the figure.
In the image below you can see two objects represented in JSON, the second of which is nested. The second object looks more like an array of elements, so let’s deal with arrays now.
PYTHON AND MONGODB – ARRAY IN JSON
An array in JSON begins with an opening bracket and ends with a closing bracket. If there are more values, they must be separated by commas.
BSON
BSON (Binary JSON) is a form of binary encoded serialization of JSON-like documents. BSON adds extensions that allow us to create other Data Types. A very important type is ObjectId which represents a unique identifier in MongoDB and is essential for going to represent the data. BSON mainly serves two purposes in MongoDB. First is the format in which the data is stored within a MongoDB database. Secondly it is an interchange format for example when we run a query on MongoDB. Both archiving and interchange take place in binary form.
DOCUMENTS AND COLLECTIONS
Within a relational database, the data is stored in tables, within which there are records made up of data that are used to define a particular information. As a first approximation we can say that a record within a relational database corresponds to a document in MongoDB. A set of documents are kept in a collection that very partially corresponds to the idea of a table in the relational world.
A MongoDB document allows us to store a data structure expressed in BSON. This is the most important element.
PYTHON AND MONGODB – EXAMPLE OF DOCUMENT
To give a first example, we can store information relating to a person in a document. All documents within MongoDB must have an _id property which is always called in this way and which establishes the uniqueness of the document within its collection. It serves the same purpose as the primary key of a relational database. We can generate one ourselves or let MongoDB create it. The data type of an _id is ObjectId
If we want to make an analogy with the relational world we can say that all the properties in MongoDB should always be the same within a collection of documents, in reality MongoDB is much more flexible, in the sense that the properties of documents can be completely different. Nothing prevents us from inserting a different structure in the documents of a collection. This happens because unlike the relational world there is no structure to which we are bound. However, one thing must be said. This is not necessarily a good solution. This can be chaos when we go to get information.
A document can have a hierarchical structure as seen in JSON and contain Array of data. In conclusion MongoDB allows us to store data in a much more flexible form than a DBMS.
WE INSTALL MONGODB AND PYMONGO
Let’s go with our Browser to the address www.mongodb.com. The figures below show the installation steps.
I am using Windows 11 and the MongoDB installation also installs MongoDBCompass a visual editor. Under Windows the database service starts automatically, if you have another operating system refer to the MongoDB documentation. To install pymongo open the terminal and type: pip3 install pymongo if you have correctly set the environment variables you should have no problems.
EXAMPLE CODE
import pymongo from pymongo import MongoClient #I connect to mongodb client = MongoClient("localhost",27017) #create a database and call it testdb db=client.testdb #create the people collection persone_coll = db.persone persone_coll.create_index([("nome",pymongo.ASCENDING)]) persone_coll.create_index([("cognome",pymongo.ASCENDING)]) persone_coll.create_index([("computer",pymongo.ASCENDING)]) #create one document p1 = {"Nome":"Mario","Cognome":"Rossi","Eta":30, "Computer":["Apple","Asus"]} #insert the document in mongodb persone_coll.insert_one(p1) #create the document p2 = {"Nome":"Giuseppe","Cognome":"Verdi","Eta":45, "Computer":["Apple"]} #insert the document in mongodb persone_coll.insert_one(p2)
import pymongo from pymongo import MongoClient #I connect to mongodb client = MongoClient("localhost",27017) #access to database called testdb db=client.testdb #create the people collection persone_coll = db.persone p=persone_coll.find_one() persone = persone_coll.find({"Computer":"Asus"}) for p in persone: print(p) print('**************') #Update operatore $set result = persone_coll.update_one({"Nome":"Giuseppe"},{"$set":{"Eta":50}}) p=persone_coll.find_one({"Nome":"Giuseppe"}) print(p) print('************************') #$gt=Greater Than operatore $gt persona = persone_coll.find_one({"Nome":{"$gt":"Giuseppe"}}) print(persona)
Leave A Comment