MongoDB is a widely used document database which is also a form of NoSQL DB. Python can interact with MongoDB through some python modules and create and manipulate data inside Mongo DB. In this article we will learn to do that. But MongoDB should already be available in your system before python can connect to it and run. To setup MongoDB in your system please visit our MongoDB tutorial here..
To interact with MongoDB we need the module names pymongo. Install it in your python environment using the below command.
pip install pymogo
We now use this python module to check for any existing DB. The below python program connects to the MongoDB service and gives a output of the list of DB names available.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") print(myclient.list_database_names())
Running the above code gives us the following result −
['Mymdb', 'admin', 'config', 'local']
A collection is similar to a table in traditional rdbms. We can next check for collections present in a specific database using the below python program.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mndb = myclient["Mymdb"] print(mndb.list_collection_names())
Running the above code gives us the following result −
['newmongocoll']
The document in MongoDB is also comparable to a row in traditional RDBMS. In this program we see how to insert a document to MongoDB using a python program. First we connect to the DB and collections and then use a dictionary to put values of the document into the collection.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mndb = myclient["Mymdb"] mycol = mndb['newmongocoll'] mydict = { "ID": "2", "Name": "Ramana" } x = mycol.insert_one(mydict) print(x)
Running the above code gives us the following result −
<pymongo.results.InsertOneResult object at 0x000002CA92A920C0>
We can also query for documents present in MongoDB using find method available in pymongo.
import pymongo myclient = pymongo.MongoClient("mongodb://localhost:27017/") mndb = myclient["Mymdb"] mycol = mndb['newmongocoll'] for x in mycol.find(): print(x)
Running the above code gives us the following result −
{'_id': ObjectId('5ef8b6f92d192421b78d32cb'), 'ID': '2', 'Name': 'Ramana'}