Connect MongoDB with Python

‘MongoDB’ serves as the database’s host process. In this setup, we initiate the MongoDB process to run in the background. It operates with several default parameters, including data storage and running on port 27017. When you run Mongo with no parameters, it defaults to connecting to localhost.

Installation

To install MongoDB,

pip install pymongo

Import Libraries 

Here  we must connect to the MongoDB server before importing libraries or interacting with any database or collection.

from pymongo import MongoClient

Connect with MongoClient 

To connect Python with MongoClient,  is a object in pymongo which is used for connecting to a MongoDB server. Hence by using URL for a local MongoDB server is //localhost:27017/ 

url = 'mongodb://localhost:27017'
client = MongoClient(url)

Access Database & Collection 

In MongoDB, data is organized into databases. Once you establish a connection, you can easily choose the database you wish to use. If the database does not already exist, MongoDB will automatically create it when you insert data.

database = client.get_database("local")
collection = database.get_collection("user")

Within these databases, there are collections, which function similarly to tables in relational databases. By selecting a specific collection, you can interact with your data. Additionally, just like databases, collections will be automatically generated whenever you insert data.

Eg:
import pymongo
from pymongo import MongoClient 

if __name__ == "__main__" : 
 print("welcome to mongodb") 
 client = pymongo.MongoClient("mongodb://localhost:27017/")
 print(client)
 db=client['sanjana']
 collection = db['mySampleCollectionsanjana']

#INSERT FILES
 dictionary = {'name':'sanjana','age':20,'location':'banglore'}
 collection.insert_one(dictionary)

#UPDATE FILES
 prev={'name':'sanya'}
 nextt ={'$set':{'location':'mumbai'}}
 collection.update_one(prev,nextt)
 collection.update_many(prev, nextt)

#DELETE FILES
 rec={'name':'sanya'}
 collection.delete_one(rec)
 up=collection.delete_many(rec)
 print(up.deleted_count)

Conclusion 

We successfully connected MongoDB with Python, making it the ideal solution for modern application backends. This powerful combination ensures robust and future-proof performance, whether for small prototypes or large-scale systems.

 

 

 

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top