Python can be used in database applications. One of the most popular NoSQL databases is MongoDB. MongoDB stores data in JSON-like documents, which makes the database very flexible and scalable. In this article, I hope to teach you the fundamentals of MongoDB in Python.
Python needs a MongoDB driver to access the MongoDB database. We recommend that you use PIP to install “PyMongo.” PIP is most likely already installed in your Python environment.
C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>python -m pip install pymongo
To test if your PyMongo has been installed successfully, run the following line of code:
import pymongo
If the above code was executed with no errors, “pymongo” is installed and ready.
To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct IP address and the name of the database you want to create.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
dblist = myclient.list_database_names()
if "mydatabase" in dblist:
print("The database exists.")
To create a collection in MongoDB, use the database object, and specify the name of the collection you want to create.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]
You can check if a collection exists in a database by listing all collections:
collist = mydb.list_collection_names()
if "customers" in collist:
print("The collection exists.")
To insert a record or document (as it is called in MongoDB) into a collection, we use the ‘insert_one()’ method.
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]
mydict = { "username": "bryan.dijkhuizen", "password": "********" }
x = mycol.insert_one(mydict)
The ‘insert_one’ method returns a value (the result of the insert). So if you want to retrieve the ID of your recently added user:
import pymongo
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = myclient["mydatabase"]
mycol = mydb["users"]
mydict = { "username": "bryan.dijkhuizen", "password": "********" }
x = mycol.insert_one(mydict)print(x.inserted_id)
#database #programming #python #mongodb #developer