MANGO DB CRUD OPERATION BY PYTHON
Published: 2024-03-05 05:34:47

Hey Reader,

My name is Seenevasaraj, and I am working as Software Developer at Luxoft India. The various project at Luxoft I am implementing automation in all viable way. Through this article I desired to provide an explanation about how we can perform CRUD operation in MongoDB using python module.

**<u>MongoDB</u>**
MongoDBdocument database to build highly available scalable internet applications,flexible schema approach,popular with development teams using agile methodologies,offering drivers for all major programming languages

Instead of storing data in tables of rows or columns like Relational databases, records in MongoDB database is document described in BSON binary representation of data,applications can then retrieve this information in JSON format

below JSON document describing a historical figure.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x9mccyx3iy9c1jatoza4.png)

Document databases highly flexible allowing variations in structure of documents&storing documents are partially complete one document can have others embedded in it,fields in document play role of columns in SQL database and then like columns, they can be indexed to increase search performance

MongoDB built on scale-out architecture,structure that allows many small machines to work together to create fast systems and handle huge amounts of data

MongoDB focused on providing developers with excellent user experience, in addition to all its other properties has made MongoDB favorite of developers worldwide for wide variety of application

**Use Of MongoDB**

MongoDB makes it easy for developers to store structured or unstructured data,using JSON-like format to store documents json format directly maps to native objects in most modern programming languages,developers do not need to think about normalizing data,MongoDB handle high volume&scale vertically or horizontally to accommodate large data

**<u>CRUD</u>**

- Creating data
- Retrieving data
- Updating data
- Deleting data

**Create**
CreateORinsert operations add new documents to collection,If collection not exist,create operations also create the collection

You can insert single document or multiple documents in single operation

MongoDB shell provides some methods to insert documents into collection:

- insert a single document-db.collection.insertOne()
- insert multiple documents-db.collection.insertMany()

**Read**
Read used to retrieve documents from collection; i.e. query collection for documents

You can specify criteria or filters,which identify documents to return

- Use to collect all data -db.collection.find()

**Update** 
Update operations modify existing documents in collection,you can update single document or multiple documents in single operation

You can specify criteria or filter which identify documents to update,filters use same syntax as read operations

- update a single document-db.collection.updateOne()
- update multiple documents-db.collection.updateMany()
- replace document-db.collection.replaceOne()

MongoDB preserves own sort order in storing of  documents,ordering internal implementation feature ,you should not rely on any particular structure within it

**Delete**
Delete operations remove existing documents from collection,you can remove single document or multiple documents in single operation

You can specify criteria or filters identify documents to remove filters use same syntax as read operations

- delete multiple documents-db.collection.deleteMany()
- delete single document-db.collection.deleteOne()

Python Module

- pymongo

**<u>CRUD Using Python</u>** 

**Prerequisites**

- MongoDB compass must be installed, to make local database connection

- After installation connect to MongoDB compass by passing the below string as input and click on the connect button.
<u>mongodb://localhost:27017/</u>


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yg6b1t5oh6ormr4hm9u.png)

**Steps to do CRUD**

- Import the pymongo package,and thendefine variable to store the MongoDB connection URL.To make connection to MongoDB server, we will use MongoClient method


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/t6wxuqrgnlswe6ujm4vy.png)

- by using client instance created, can access databases in MongoDB,display databases use list_database_names()

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/de4l8g5y6thkxmjtkty3.png)

- In MongoDB, unless we add any document to database, we cannot see database created in list of available databases,to create document, we need to create collection in database which stores documents

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/glf5dmwl51acrd9k76bx.png)


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cc5wucwbw65tvm6h4b74.png)

**Inserting documents**

Inserting documents into collection can be done two ways

- insert single document - insert_one() method

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xg4n2mzrpubn3yukhqc0.png)

- insert multiple document - insert_many() method

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y7w9w2f880olqpibb2hf.png)

**Retrieving**

Retrieving data can be done in two ways

retrieve single document - find_one() method,need to pass query as parameter to find_one() method .find_one() method search collection and it will return first hit document

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ae95hy7izta9sw6n22hb.png)

retrieve multiple documents - find_many(),find_many() is cursor object-use for loop to loop over cursor object

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9edvjnx45vp62157ob6w.png)

**Updating**

Updating documents can be done by two ways

update single document - update_one() method

to update documents,need to provide 2 parameters into method,first parameter is filter parameter&second parameter is update parameter,filter parameter is query matches document to be updated, Update parameter is modifications to be applied for document

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkveyleqxscu253hnf2j.png)

update multiple documents - update_many()

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xfxoe5eisu64h7ky2dav.png)

**Deleting** 

Deleting documents can be done by two ways

delete single document - delete_one() method by passing query as parameter

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2ilqhdbcktbvdvoxkp0n.png)

delete multiple documents - delete_many() 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8pbpe9fyovhexuxdrjlg.png)

**Dropping collection** 
drop collection - drop() method,drop method will erase entire data in collection 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8qsuz3jy5pgvhj2rvzxm.png)

**<u>Conclusion</u>**
MongoDB accommodate wide Varity of data format, So it can be used for lot of purpose and along with python we can perform CRUD operation effectively and automated way.